示例数据框:
library(tidyverse)
example <- data.frame(matrix(sample.int(15),5,3),
sample(c("A","B","C"),5,replace=TRUE) ) %>%
`colnames<-`( c("A","B","C","choose") ) %>% print()
输出:
A B C choose
1 9 12 4 A
2 7 8 13 C
3 5 1 2 A
4 15 3 11 C
5 14 6 10 B
“选择”列表示应从 A、B、C 列中选择哪个值
我对“结果”列的简单解决方案:
cols <- c(A=1,B=2,C=3)
col_index <- cols[example$choose]
xy <- cbind(1:nrow(example),col_index)
example %>% mutate(result = example[xy])
输出:
A B C choose result
1 9 12 4 A 9
2 7 8 13 C 13
3 5 1 2 A 5
4 15 3 11 C 11
5 14 6 10 B 6
我确信 dplyr 有一个更优雅的解决方案, 但我尝试“rowwise”或“accross”失败了。
是否有可能获得单行解决方案?
最佳答案
有效的选择是使用行/列索引
example$result <- example[1:3][cbind(seq_len(nrow(example)),
match(example$choose, names(example)))]
对于dplyr
,我们可以将get
与rowwise
结合使用
library(dplyr)
example %>%
rowwise %>%
mutate(result = get(choose)) %>%
ungroup
或者使用 cur_data()
代替 get
example %>%
rowwise %>%
mutate(result = cur_data()[[choose]]) %>%
ungroup
或者带有行/列索引的矢量化选项
example %>%
mutate(result = select(., where(is.numeric))[cbind(row_number(),
match(choose, names(example)))])
关于r - 使用管道运算符对同一行中另一列的变量值进行寻址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70049751/