gpt4 book ai didi

r - 创建一个新的数据框列,该列是其他列的组合

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

我有 3 列 a 、 b 、c ,我想借助列心情将它们组合成一个新列,如下所示:

如果 mod= 1 ,数据来自 a

如果 mod=2 ,数据来自 b

如果mode=3,数据来自c

示例

    mode     a     b      c
1 2 3 4
1 5 53 14
3 2 31 24
2 12 13 44
1 20 30 40

输出

    mode     a     b      c       combine
1 2 3 4 2
1 5 53 14 5
3 2 31 24 24
2 12 13 44 13
1 20 30 40 20

最佳答案

我们可以使用行/列索引来从数据集中获取值。此处,对行序列 (seq_len(nrow(df1))) 和列索引 ('mode') 进行cbind编辑以创建一个矩阵 从数据集子集中提取相应的值

df1$combine <- df1[2:4][cbind(seq_len(nrow(df1)), df1$mode)]
df1$combine
#[1] 2 5 24 13 20

数据

df1 <- structure(list(mode = c(1L, 1L, 3L, 2L, 1L), a = c(2L, 5L, 2L, 
12L, 20L), b = c(3L, 53L, 31L, 13L, 30L), c = c(4L, 14L, 24L,
44L, 40L)), class = "data.frame", row.names = c(NA, -5L))

关于r - 创建一个新的数据框列,该列是其他列的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57292695/

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