Home > Back-end >  Subset of a data frame according to the combination of rows and column indices
Subset of a data frame according to the combination of rows and column indices

Time:08-09

I have a data.frame (called df) like this one:

structure(list(GWeek = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Team1 = c(33, 
24, 30, 18, 31, 37, 26, 35, 19, 22), Team2 = c(21, 24, 33, 21, 
28, 23, 28, 32, 24, 26), Team3 = c(25, 30, 27, 21, 35, 26, 28, 
25, 29, 33), Team4 = c(30, 29, 28, 21, 33, 18, 17, 29, 32, 27
), Team5 = c(12, 18, 31, 21, 41, 30, 27, 31, 18, 24), Team6 = c(30, 
23, 31, 27, 35, 21, 24, 41, 43, 24)), class = "data.frame", row.names = c(NA, 
-10L))

which looks like that:

   GWeek Team1 Team2 Team3 Team4 Team5 Team6
1      1    33    21    25    30    12    30
2      2    24    24    30    29    18    23
3      3    30    33    27    28    31    31
4      4    18    21    21    21    21    27
5      5    31    28    35    33    41    35
6      6    37    23    26    18    30    21
7      7    26    28    28    17    27    24
8      8    35    32    25    29    31    41
9      9    19    24    29    32    18    43
10    10    22    26    33    27    24    24

I want to get a vector with some values of this table. These values are indicated by the combination of two vectors:

# Row indices
  r.idx <- c(4,5,6,9,10)
# Column indices
  c.idx <- c("Team5", "Team3", "Team6", "Team4", "Team2")

So, what I want is a vector with the following values:

 df[4,"Team5"], df[5,"Team3"], df[6,"Team6"], df[9,"Team4"], df[10, "Team2"]

As my dataset is bigger and the number of combinations is very high, I am looking for a way to get the values of df corresponding to the combination of the i-th element of r.idx (row) and c.idx(column).

Any suggestion is welcome.

CodePudding user response:

You could use diag:

diag(as.matrix(df[r.idx, c.idx]))
#[1] 21 35 21 32 26
  • Related