如何使用mutate计算R中每列的焓?
我想用这个公式来计算焓。 我想将该功能调整到包含温度和压力的TIBLE表格,但失败了。 例如,我想添加焓行如何使用mutate计算R中每列的焓?,r,function,dplyr,mutate,tibble,R,Function,Dplyr,Mutate,Tibble,我想用这个公式来计算焓。 我想将该功能调整到包含温度和压力的TIBLE表格,但失败了。 例如,我想添加焓行 sample_table temp pressure 800 16 900 17 1000 18 sample_table_add_enthalpy <- sample_table %>% mutate(enthalpy = hTp(temp, pressure)) 在这种情况下,计算仅适用于第一列。 我应该如何使用mutate计算所有列?在仔细考虑了您的
sample_table
temp pressure
800 16
900 17
1000 18
sample_table_add_enthalpy <- sample_table %>%
mutate(enthalpy = hTp(temp, pressure))
在这种情况下,计算仅适用于第一列。
我应该如何使用mutate计算所有列?在仔细考虑了您的问题后,现在我知道您不是在谈论多个列。相反,您似乎希望有一个可以处理多行数据的函数 这里我提供了两种解决方案。第一种方法是使用
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
在我看来(尽管我不确定),hTp
的参数应该是单变量,而不是向量。突变(焓=mapply(hTp,温度,压力))是否有效?
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
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