gpt4 book ai didi

r - 如何使用列索引从 R 中的列收集值

转载 作者:行者123 更新时间:2023-12-03 23:08:16 24 4
gpt4 key购买 nike

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 中执行此操作的最简单方法是什么?

谢谢!

最佳答案

在基础 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))

关于r - 如何使用列索引从 R 中的列收集值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60886455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com