首页 > 解决方案 > Subset a data.frame based on row-column combinations

问题描述

I want to subset a data.frame based on subscripts stored in another data.frame.

So for example, if I have the following data.frame:

 set.seed(1)
 x <- rnorm(5)
 df <- data.frame(x,x*x, x*2, x/2)

 df
           x      x...x      x...2         x.2
1 -0.6264538 0.39244438 -1.2529076 -0.31322691
2  0.1836433 0.03372487  0.3672866  0.09182166
3 -0.8356286 0.69827518 -1.6712572 -0.41781431
4  1.5952808 2.54492084  3.1905616  0.79764040
5  0.3295078 0.10857537  0.6590155  0.16475389

I want to subset the values of [1,3] and [2,4]. Thus the data.frame which I want to use as keys for subsetting looks like this:

sub <- data.frame(row = c(1,2), col = c(3,4))

sub
  row col
1   1   3
2   2   4

My result should look like this:

c(df[1,3], df[2,4])
[1] -1.25290762  0.09182166

However, it should all be done within one df[*]

I know this is easy but I still cannot figure it out! So thanks a lot in advance.

标签: rsubset

解决方案


将其转换为matrix子集

df[as.matrix(sub)]
#[1] -1.25290762  0.09182166

推荐阅读