简体   繁体   中英

How to subset matrices in an list in R?

Currently, I have a list of 500 elements, named List.500 . In each list, I have 3 vectors and 1 matrix. The first element is:

> List.500[[1]]
$two_values
$two_values$bin
[1] 0 1

$grid_points$grid
 [1] 0.05000000 0.06836735 0.08673469 0.10510204 0.12346939 0.14183673 0.16020408
 [8] 0.17857143 0.19693878 0.21530612 0.23367347 0.25204082 0.27040816 0.28877551



$mean_0
 [1] 14.48597 14.49662 14.51089 14.52915 14.55242 14.58129 14.61866 14.66572 14.72186
[10] 14.79531 14.88589 14.99356 15.13048 15.29701 

$mean_1
 [1] 16.48597 16.49662 16.51089 16.52915 16.55242 16.58129 16.61866 16.66572 16.72186
[10] 16.79531 16.88589 16.99356 17.13048 17.29701 

$mean_grid
      g=0.05   g=0.07   g=0.09   g=0.11   g=0.12   g=0.14   g=0.16   g=0.18    g=0.2
bin=0 14.48597 14.49662 14.51089 14.52915 14.55242 14.58129 14.61866 14.66572 14.72186
bin=1 16.48597 16.49662 16.51089 16.52915 16.55242 16.58129 16.61866 16.66572 16.72186
      g=0.22   g=0.23   g=0.25   g=0.27   g=0.29    
bin=0 14.79531 14.88589 14.99356 15.13048 15.29701 
bin=1 16.79531 16.88589 16.99356 17.13048 17.29701 

I would like to subset out only the 1st, 2nd, and 3rd elements from each of the 2 vectors (not including the first vector named two_values$bin and 1 matrix (1st, 2nd, 3rd columns), for each of the 500 elements of List.500 . I want to leave two_values$bin alone.

Ideally, I would like to get:

> List.500[[1]]
$two_values
$two_values$bin
[1] 0 1

$grid_points$grid
 [1] 0.05000000 0.06836735 0.08673469

$mean_0
 [1] 14.48597 14.49662 14.51089

$mean_1
 [1] 16.48597 16.49662 16.51089

$mean_grid
      g=0.05   g=0.07   g=0.09
bin=0 14.48597 14.49662 14.51089
bin=1 16.48597 16.49662 16.51089

for each of the 500 elements in List.500 . Is there a simple way to do this without resorting to breaking the list apart and looping? Thanks.

As commented, you can use rapply . I think the elements of your list follow a pattern but for the purpose of this demonstration, I used the following data.

set.seed(123)
List.500 <- lapply(1:3, function(x) list(two_values = list(bin = 0:1),
                 grid_points = list(grid = runif(16, 0,.3)),
                 mean_0 = runif(14, 14, 16),
                 mean_1 = runif(14, 16, 18),
                 mean_grid = matrix(runif(28, 14, 18), nrow = 2, byrow = TRUE)))

The following code will do exactly what you wanted.

rapply(List.500, 
       function(x) {if(is.matrix(x)) {x[,1:3]} else {
         if(length(x) == 2) {x} else {x[1:3]}
         }}, 
       how = "replace")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM