是否有一种方法可以从一个字符串指定的列中调用数据,该字符串不同于数据帧的不同行?



在本例中,变量"colnumber"表示要提取哪一列的数据。

col1 <- c("a", "b", "c")
col2 <- c("b", "a", "c")
col3 <- c("c", "b", "a")
colnumber <- c(1, 2, 3) 
df <- data.frame(col1, col2, col3, colnumber)

我尝试创建一个变量a_col,并从"number"指定的编号列复制数据。使用paste0创建字符串,然后将其转换为符号:

df %%
mutate(a_col = !!sym(paste0("col", colnumber)))

我期待的是一个新的变量a_col,它的值为"a"对于所有3行。

相反,我得到以下错误消息:

local_error_context(dots = dots, .index = i, mask = mask)出错:承诺已经在评估:递归默认参数引用或更早的问题?

基于dplyr的解决方案,使用行mutate():

library(dplyr)
df %>%
rowwise %>%
mutate(a_col = cur_data()[[paste0("col", colnumber)]]) %>%
ungroup()

或使用sapply()索引到每一行的base R解决方案:

df$a_col <- sapply(
seq(nrow(df)), 
(row) df[row, paste0("col", df[row, "colnumber"])]
)
df

两种方法的结果:

col1 col2 col3 colnumber a_col
1    a    b    c         1     a
2    b    a    b         2     a
3    c    c    a         3     a

注意,如果col1,col2等是数据集中的第一列,第二列等,您可以省略paste0("col"),只使用数字索引。

TRY THIS:

library(purrr)
df %>% mutate(a_col = map(colnumber, ~df[[paste0("col", .x)]]))

Base R解:

df$a_col <- vapply(
seq_along(df$colnumber), 
function(i){
df[i, df$colnumber[i], drop = TRUE]
},
character(1)
)

使用行/列索引的矢量化操作

df$a_col <- df[1:3][cbind(seq_len(nrow(df)), df$colnumber)]

与产出

> df
col1 col2 col3 colnumber a_col
1    a    b    c         1     a
2    b    a    b         2     a
3    c    c    a         3     a

最新更新