如何使用列索引在R中从列中收集值

4
x y z column_indices 
6 7 1      1,2
5 4 2       3
1 3 2      1,3

我有一个包含需要收集的值的列索引,我想要创建一个类似下面的东西:

x y z column_indices values
6 7 1      1,2        6,7
5 4 2       3          2
1 3 2      1,3        1,2

什么是在R中实现这个的最简单方式?
谢谢!

您可以通过点击投票按钮旁边的复选标记来接受一个答案,选择最适合您的答案。 - Ronak Shah
2个回答

2

在基础R中,我们可以使用apply函数,将column_indices按照','进行分割,转换为整数,并从行中获取相应的值。

df$values <- apply(df, 1, function(x) {
   inds <- as.integer(strsplit(x[4], ',')[[1]])
   toString(x[inds])
})

df
#  x y z column_indices values
#1 6 7 1            1,2   6, 7
#2 5 4 2              3      2
#3 1 3 2            1,3   1, 2

数据

df <- structure(list(x = c(6L, 5L, 1L), y = c(7L, 4L, 3L), z = c(1L, 
2L, 2L), column_indices = structure(c(1L, 3L, 2L), .Label = c("1,2", 
"1,3", "3"), class = "factor")), class = "data.frame", row.names = c(NA, -3L))

2

使用 dplyrtidyr 的一种解决方案可能是:

df %>%
 pivot_longer(-column_indices) %>%
 group_by(column_indices) %>%
 mutate(values = toString(value[1:n() %in% unlist(strsplit(column_indices, ","))])) %>%
 pivot_wider(names_from = "name", values_from = "value")

  column_indices values     x     y     z
  <chr>          <chr>  <int> <int> <int>
1 1,2            6, 7       6     7     1
2 3              2          5     4     2
3 1,3            1, 2       1     3     2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接