Home > Net >  Select row by its list index in r
Select row by its list index in r

Time:10-15

I would like to extract the row by its list index. I tried to search in stackoverflow but most of the solution only works for certain index (e.g. sapply(list,"[[,1) (This select every first row) or sapply(list,"[,1:2) (This select every first and second rows)).

Here is an example:

set.seed(123)
x<-data.frame(matrix(runif(9),ncol=3))
y<-data.frame(matrix(runif(9),ncol=3))
z<-data.frame(matrix(runif(9),ncol=3))

lst<-list(x,y,z)

lst
[[1]]
         X1        X2        X3
1 0.2875775 0.8830174 0.5281055
2 0.7883051 0.9404673 0.8924190
3 0.4089769 0.0455565 0.5514350

[[2]]
         X1        X2         X3
1 0.4566147 0.6775706 0.89982497
2 0.9568333 0.5726334 0.24608773
3 0.4533342 0.1029247 0.04205953

[[3]]
         X1        X2        X3
1 0.3279207 0.6928034 0.6557058
2 0.9545036 0.6405068 0.7085305
3 0.8895393 0.9942698 0.5440660

Desired output:

lst
[[1]] #select first row
         X1        X2        X3
1 0.2875775 0.8830174 0.5281055

[[2]] #select second row
         X1        X2         X3
1 0.9568333 0.5726334 0.24608773

[[3]] #select third row
         X1        X2        X3
1 0.8895393 0.9942698 0.5440660

CodePudding user response:

We may use imap. As the list is unnamed, the .y will be the sequence index of the list, which we used in slice to subset the rows

library(purrr)
library(dplyr)
imap(lst, ~ .x %>%
     slice(.y))

-output

[[1]]
         X1        X2        X3
1 0.2875775 0.8830174 0.5281055

[[2]]
         X1        X2        X3
1 0.9568333 0.5726334 0.2460877

[[3]]
         X1        X2       X3
1 0.8895393 0.9942698 0.544066

Or using base R with Map

Map(function(x, i) x[i,], lst, seq_along(lst))

-output

[[1]]
         X1        X2        X3
1 0.2875775 0.8830174 0.5281055

[[2]]
         X1        X2        X3
2 0.9568333 0.5726334 0.2460877

[[3]]
         X1        X2       X3
3 0.8895393 0.9942698 0.544066
  •  Tags:  
  • r
  • Related