2

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.

Karl A
  • 165
  • 11
  • Thank you very much for the answers so far! This was exactly what I was looking for. While implementing, I got a follow-up question: How does this work in data.tables? Because if I use the approach by akrun and Ronak Shah, I get an error saying `Error in `[.data.table`(mb_profit_df[[56]], cbind(mb_profit_max_pos[[56]][, : i is invalid type (matrix). Perhaps in future a 2 column matrix could return a list of elements of DT (in the spirit of A[B] in FAQ 2.14). Please report to data.table issue tracker if you'd like this, or add your comments to FR #657.` – Karl A Jan 09 '19 at 13:33
  • 1
    Please check the edit from my post – akrun Jan 09 '19 at 13:37
  • ok this was my first thought as well! I hoped for a neater solution, but I will work with this :) – Karl A Jan 09 '19 at 13:39
  • Why was akrun's post deleted? – Karl A Jan 09 '19 at 14:41
  • Related post [here](https://stackoverflow.com/questions/44797095/get-value-of-a-matrix-with-row-index-and-column-index) – akrun Jan 09 '19 at 15:21

1 Answers1

1

Convert it into matrix and subset

df[as.matrix(sub)]
#[1] -1.25290762  0.09182166
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213