如何通过对 R 中的每一列使用 mutate 来计算焓?
How to calculate enthalpy by using mutate for each column in R?
我想使用 steam table function 来计算焓。
我想将该功能调整为包含温度和压力的 Tibble table,但失败了。
例如,我想添加焓行。
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 计算所有列?
在进一步思考你的问题后,我现在明白你不是在谈论多个专栏。相反,您似乎想要一个可以处理多行数据的函数。
这里我提供了两种解决方案。第一个是使用 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
第二个是使用 purrr
包中的 map2
来向量化操作。
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
我想使用 steam table function 来计算焓。 我想将该功能调整为包含温度和压力的 Tibble table,但失败了。 例如,我想添加焓行。
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 计算所有列?
在进一步思考你的问题后,我现在明白你不是在谈论多个专栏。相反,您似乎想要一个可以处理多行数据的函数。
这里我提供了两种解决方案。第一个是使用 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
第二个是使用 purrr
包中的 map2
来向量化操作。
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