r - 如何通过对 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 计算所有列?
解决方案
在对您的问题进行了更多思考之后,现在我了解到您不是在谈论多个专栏。相反,您似乎想要一个可以处理多行数据的函数。
在这里,我提供了两个解决方案。第一个是使用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
第二种是使用map2
frompurrr
包对操作进行矢量化。
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
推荐阅读
- css - 为什么在使用相同的倾斜时我的字体大小看起来会有所不同?
- codeceptjs - 使用 CodeceptJS 在 Chromium 中运行自定义 JavaScript?
- anaconda - Theano 无法识别 Anaconda 新编译器
- c++ - 查找最长的公共子串
- java - 如何通过 RestController 代理内部 mjpeg 端点
- apache-spark - 为什么 DROP TABLE 忽略子句 IF EXISTS?
- java - 如何在小数点后四舍五入到最接近的 5
- java - `commitNow()` 和 `postDelayed` 如何使这段代码工作?
- javascript - GulpUglifyError:无法缩小 JavaScript - 排序映射
- python - 如何将键和值(列表)附加到新字典?