gpt4 book ai didi

r - 使用列名变量按行选择数据框值

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

假设我有一个如下所示的数据框:

dframe = data.frame(x = c(1, 2, 3), y = c(4, 5, 6))
# x y
# 1 1 4
# 2 2 5
# 3 3 6
以及一个列名向量,数据框的每行一个: colname = c('x', 'y', 'x')对于数据框的每一行,我想从向量中的相应列中选择值。类似于 dframe[, colname]但对于每一行。
因此,我想获得 c(1, 5, 3) (即第 1 行:col“x”;第 2 行:col“y”;第 3 行:col“x”)

最佳答案

我最喜欢的旧矩阵索引会解决这个问题。只需传递具有相应行/列索引的 2 列矩阵:

rownames(dframe) <- seq_len(nrow(dframe))
dframe[cbind(rownames(dframe),colname)]
#[1] 1 5 3

或者,如果您不想添加行名:
dframe[cbind(seq_len(nrow(dframe)), match(colname,names(dframe)))]
#[1] 1 5 3

关于r - 使用列名变量按行选择数据框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51093685/

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