首页 > 解决方案 > 如何通过对 R 中的每一列使用 mutate 来计算焓?

问题描述

我想用蒸汽表函数计算焓。我想将该函数调整为包含温度和压力的 Tibble 表,但失败了。例如,我想添加焓行。

sample_table    

temp pressure
800  16
900  17
1000 18

sample_table_add_enthalpy <- sample_table %>%
  mutate(enthalpy = hTp(temp, pressure))

结果是

temp pressure enthalpy
800  16     3375.08509
900  17     3375.08509
1000 18     3375.08509

在这种情况下,计算仅适用于第一列。我应该如何使用 mutate 计算所有列?

标签: rfunctiondplyrtibble

解决方案


在对您的问题进行了更多思考之后,现在我了解到您不是在谈论多个专栏。相反,您似乎想要一个可以处理多行数据的函数。

在这里,我提供了两个解决方案。第一个是使用Vectorize函数将您的函数转换为可以生成矢量化输出的版本。

library(IAPWS95)
library(tidyverse)

hTp_vectorize <- Vectorize(hTp)

sample_table_add_enthalpy <- sample_table %>%
  mutate(enthalpy = hTp_vectorize(temp, pressure))

sample_table_add_enthalpy
#   temp pressure   enthalpy
# 1  800       16 3375.08509
# 2  900       17 3636.88144
# 3 1000       18 3889.57761

第二种是使用map2frompurrr包对操作进行矢量化。

sample_table_add_enthalpy <- sample_table %>%
  mutate(enthalpy = map2(temp, pressure, hTp))

sample_table_add_enthalpy
#   temp pressure   enthalpy
# 1  800       16 3375.08509
# 2  900       17 3636.88144
# 3 1000       18 3889.57761

推荐阅读