r - 使用管道运算符对同一行中另一列的变量值进行寻址

标签 r dplyr pipe

示例数据框:

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,我们可以将getrowwise结合使用

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/

相关文章:

r - 为ggplot2中的每个面板添加具有不同截距的垂直线

r - 具有分位数和其他功能的 dplyr summarise_all

r - 当按多个列分组时,如何在 dplyr 中命名 group_split 的列表

linux - Python 2.7 子进程 : tail -f | grep

r - 在 rshiny 中的 mathjax 中的单词之间添加空格

r - 动态分配/引用 data.table 中的列名(在 i、j 和 by 中)

bash - 为什么管道输入到 "read"仅在馈入 "while read ..."构造时才有效?

r - 按组提取变量最小值对应的行

r - Group_by 然后用 dplyr 过滤