Home > Software design >  Is there a way to index match both rows and columns in R?
Is there a way to index match both rows and columns in R?

Time:10-16

I have a tibble and want to create a list of specific values in that tibble based on lists I have made of row and column positions. For example I have a list of row positions; row = [1,4,6,2,5], and column positions; column = [2,3,7,3,6], and I want to make a list of the values of my tibble at [1,2],[4,3],[6,7],[2,5] and [5,6]. If I simply say my_list = my_tibble[row,column] I get a tibble as it takes every row position with every column position, instead of just the first with the first, second with second etc. This feels like it should be simple but I've been battling it for so long!

CodePudding user response:

You can simply loop through your row/col vector with lapply.

my_df <- data.frame(replicate(10,sample(0:100,10,rep=TRUE)))
my_df
#>    X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
#> 1  40 52 48  5 70 69 91 80 91   8
#> 2  25 96 56 82 51 15 89 53  9  68
#> 3   3 57 32 63 76 71 11 83 19  45
#> 4  31 35 31 65 27 30 49 71  0  14
#> 5  80 53 97 22 61 99 80 61 50  72
#> 6  23 44 19 75 88 52  8 89 60  31
#> 7  92 24 58 51  6 96 61 73 70  68
#> 8  44 18 15 15 57 81  4 91 49  49
#> 9  70 68 12 40 48 38 53 57 68   2
#> 10 44 29 70 89 26 47 47 93 91  71
rows <- c(1,4,6,2,5)
cols <- c(2,3,7,3,6)
                        

lapply(seq_along(rows), function(x) return(my_df[rows[x], cols[x]]))   
#> [[1]]
#> [1] 52
#> 
#> [[2]]
#> [1] 31
#> 
#> [[3]]
#> [1] 8
#> 
#> [[4]]
#> [1] 56
#> 
#> [[5]]
#> [1] 99

CodePudding user response:

Similar to tacoman's answer, mapply allows you to iterate through multiple vectors with a function. Here the function takes two arguments (the nth element of each vector) and the vectors are your row and column indices.

set.seed(42)
my_df <- data.frame(replicate(10, sample(0:100, 10, rep = TRUE)))
my_df
#>     X1 X2  X3 X4 X5 X6 X7  X8 X9 X10
#> 1   48 70  35 41 85 48 39  34 17  90
#> 2  100 99 100 23 17 25  4  92 68  12
#> 3   64 88  94 29 91  5 32  15 54  52
#> 4   24 36   4 42 68  5 48 100 39  53
#> 5   73 19  83 14  3  1 99  91 20  82
#> 6   99 25  33 21 97  2 72  68 99  31
#> 7   17  2  91 57 49 20 28  91 56  79
#> 8   48 40   2  7 98  1 75   1 99  59
#> 9   46 88  57 35 87 57 83  81 41  28
#> 10  23 26  96 67 86  9  8  23 17  80
rows <- c(1, 4, 6, 2, 5)
cols <- c(2, 3, 7, 3, 6)
                        
mapply(function(i, j) my_df[i, j], rows, cols)
#> [1]  70   4  72 100   1
  •  Tags:  
  • r
  • Related