问题
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 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
回答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