r - R 在 for 循环中使用 mutate()
问题描述
我想在 for 循环中使用 mutate() ,附加列名称如下:
y_1 y_2 y_3
这是我的代码:
table1 <- tibble(
x = rep(1:3, each = 1)
)
table1
# A tibble: 3 x 1
x
<int>
1 1
2 2
3 3
table2 <- tibble(
a1 = c(10, 20),
a2 = c(30, 60)
)
table2
# A tibble: 2 x 2
a1 a2
<dbl> <dbl>
1 10 30
2 20 40
compute_y <- function(table1, table2){
table2[1] + table2[2] * table1$x
}
for (i in 1:nrow(table2)){
output = compute_y(table1, as.numeric(table2[i,]))
label = str_c("y_", i)
table1 <- mutate(table1, label = output)
}
table1
# A tibble: 3 x 2
x label
<int> <dbl>
1 1 80
2 2 140
3 3 200
我需要做什么才能获得:
table1
# A tibble: 3 x 2
x y_1 y_2
<int> <dbl> <dbl>
1 1 40 80
2 2 70 140
3 3 100 200
解决方案
要将变量分配为列名,您必须使用非标准评估。所以要使用值label
作为名称使用!!
,然后是:=
library(dplyr)
library(rlang)
for (i in 1:nrow(table2)){
output = compute_y(table1, as.numeric(table2[i,]))
label = str_c("y_", i)
table1 <- mutate(table1, !!label := output)
}
table1
# A tibble: 3 x 3
# x y_1 y_2
# <int> <dbl> <dbl>
#1 1 40 80
#2 2 70 140
#3 3 100 200
推荐阅读
- c# - 获取授权组所需的 DirectoryEntry 调用方法名称
- sql-server - 在 SSIS 错误中查找转换:不会阻止插入现有记录
- python - 如何使用 OpenCV Python 检测对象的边缘点?
- typescript - 我的函数没有返回正确的类型,这可能吗?
- ruby-on-rails - LoadError (Unable to autoload constant Api::V1::UserTokenController) Knock Gem
- jasmine - 茉莉花得到当前的测试结果
- javascript - 如何在数组检查javascript中忽略大写/小写
- python - 使用 PyYaml 解析可能无效的 YAML
- java - 如何从双值创建对象列表?
- html - 向用户提供大容量图像的安全方法?