Extract values from data frame using data frame of indexes - R

孤者浪人 提交于 2021-02-05 06:59:05

问题


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

回答1:


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

or otherwise, cbind the columns of 'pos' as cbind of vectors 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



回答2:


You could also do this with a function inside a call to sapply, working down the rows of pos:

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


来源:https://stackoverflow.com/questions/40692736/extract-values-from-data-frame-using-data-frame-of-indexes-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!