使用索引的数据帧从数据帧中提取值-R [英] Extract values from data frame using data frame of indexes - R
问题描述
我有一个有用信息的数据框:
I have a data frame of useful information:
X = c(1,2,3,4,5,6,7,8,9,10)
Y = c(5,4,3,2,1,0,1,2,3,4)
Z = c(11,12,13,14,15,16,17,18,19,20)
df <- data.frame(X, Y, Z)
还有行和列位置的数据框:
And a data frame of row and column positions:
row <- c(6,2,5)
column <- c(1,2,3)
pos <- data.frame(row, column)
我想使用一些函数( fun
),该函数使用 pos
中的列和行位置返回 df
中所占的值这些位置,例如
I would like to use some function (fun
) that uses the column and row positions in pos
to return the values in df
occupying those positions, e.g.
fun(df, pos$row, pos$column)
[1] 6 4 15
我以为我可以这样做,但无济于事
I thought I could do it like this, but to no avail
df[c(pos$row),c(pos$col)]
推荐答案
行/列索引用作矩阵
,因此我们将'pos'转换为矩阵
并将其用作提取值的行/列索引.
The row/column index works as a matrix
, so we convert to the 'pos' to a matrix
and use that as row/column index for extracting the values.
df[as.matrix(pos)]
否则, cbind
将'pos'的列作为 vector
s的 cbind
返回一个 matrix
or otherwise, cbind
the columns of 'pos' as cbind
of vector
s returns a matrix
df[cbind(pos$row, pos$column)]
这可以转换为函数
This can be converted to a function
fExtract <- function(dat, indexDat){
dat[as.matrix(indexDat)]
}
fExtract(df, pos)
#[1] 6 4 15
这篇关于使用索引的数据帧从数据帧中提取值-R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!