使用列名变量按行选择数据框值 [英] Select data frame values row-wise using a variable of column names
问题描述
假设我有一个如下所示的数据框:
Suppose I have a data frame that looks like this:
dframe = data.frame(x = c(1, 2, 3), y = c(4, 5, 6))
# x y
# 1 1 4
# 2 2 5
# 3 3 6
还有一个列名向量,数据框的每一行一个:
And a vector of column names, one per row of the data frame:
colname = c('x', 'y', 'x')
对于数据框的每一行,我想从向量中的相应列中选择值.类似于 dframe[, colname]
但对于每一行.
For each row of the data frame, I would like to select the value from the corresponding column in the vector. Something similar to dframe[, colname]
but for each row.
因此,我想获得 c(1, 5, 3)
(即第 1 行:colx";第 2 行:coly";第 3 行:colx";x")
Thus, I want to obtain c(1, 5, 3)
(i.e. row 1: col "x"; row 2: col "y"; row 3: col "x")
推荐答案
我最喜欢的旧矩阵索引会解决这个问题.只需传递带有相应行/列索引的 2 列矩阵:
My favourite old matrix-indexing will take care of this. Just pass a 2-column matrix with the respective row/column index:
rownames(dframe) <- seq_len(nrow(dframe))
dframe[cbind(rownames(dframe),colname)]
#[1] 1 5 3
或者,如果您不想添加行名:
Or, if you don't want to add rownames:
dframe[cbind(seq_len(nrow(dframe)), match(colname,names(dframe)))]
#[1] 1 5 3
这篇关于使用列名变量按行选择数据框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!