简体   繁体   English

使用索引的数据框从数据框中提取值-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)

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, eg 我想使用一些函数( fun ),该函数使用pos的列和行位置来返回df占据这些位置的值,例如

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)]

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. 行/列索引用作matrix ,因此我们将'pos'转换为matrix并将其用作行/列索引以提取值。

df[as.matrix(pos)]

or otherwise, cbind the columns of 'pos' as cbind of vector s returns a matrix 或以其它方式, cbind的“POS”的列作为cbindvector小号返回一个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

You could also do this with a function inside a call to sapply , working down the rows of pos : 您也可以通过调用sapply内的函数来完成此sapply ,从而处理pos的行:

sapply(seq(nrow(pos)), function(i) df[pos$row[i], pos$column[i]])
[1]  6  4 15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM