R在for循环中使用mutate()
我想在for循环中使用mutate(),附加列名如下的列: y_1 y_2 y_3 这是我的密码:R在for循环中使用mutate(),r,for-loop,mutate,R,For Loop,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
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要将变量指定为列名,必须使用非标准求值。所以使用标签的值作为名称使用代码>后接:=
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
库(dplyr)
图书馆(rlang)
适用于(i/1:nrow(表2)){
输出=计算(表1,如.numeric(表2[i,]))
标签=str_c(“y_”,i)
表1我们可以使用base R
来实现这一点
for(i in seq_len(nrow(table2))) {
output <- compute_y(table1, as.numeric(table2[i,]))
label <- paste0("y_", i)
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
for(i在下文(表2))中){
输出谢谢!我喜欢这两个版本(base R和rlang软件包)。我是一个初学者,所以我将标记base R版本作为答案。
for(i in seq_len(nrow(table2))) {
output <- compute_y(table1, as.numeric(table2[i,]))
label <- paste0("y_", i)
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