1

I have a list of 100 matrices where I need to delete multiple rows in each matrix of the list.

[[99]]
               x         y         z
 [1,]  40.614014 -0.419043  2.358242
 [2,]  40.750373  0.060505 -2.043480
 [3,]  26.927057 -6.738943  0.920763
 [4,]  27.508456  6.472744  0.625628
 [5,] -35.356189 -9.982903  2.070342
 [6,]         NA        NA        NA
 [7,]  14.443243 -7.074174  1.263049
 [8,]   1.972223 -7.739286  1.546097
 [9,] -10.520837 -8.039801  1.702196
[10,] -22.998039 -8.577798  1.804459
[11,]         NA        NA        NA
[12,] -19.796859  0.134456 -3.754037
[13,]         NA        NA        NA
[14,]         NA        NA        NA
[15,]         NA        NA        NA
[16,]         NA        NA        NA
[17,]   5.715001  0.014768 -5.151677
[18,]  -0.223313 -3.261829 -4.483909
[19,]  -6.794073 -0.090648 -5.349939
[20,]  -0.176161  3.251524 -5.227120
[21,]         NA        NA        NA
[22,]         NA        NA        NA
[23,]         NA        NA        NA
[24,]         NA        NA        NA
[25,]  29.436459  0.077276 -3.853158
[26,]  17.757341  0.162857 -4.573970
[27,] -14.035571 -0.022803 -5.535868
[28,]  14.443242  7.245918  1.263049
[29,]  14.443244  0.000001  5.730853
[30,]  14.443245 -0.000001 -4.752353
[31,] -29.435556 -5.619648  0.549797

For example I'd like to delete all but rows 3,5,7,8,9,10.

I have tried this:

lapply(lst, `[`, -11,)

But was unable to get it to do multiple rows at a time and considering that it changes the row names each it time, it gets confusing to do apply this every time to end with the rows I want to keep.

I found this for dataframes:

myData[-c(2, 4, 6), ]

Is there anything similar for lists?

Also, is it possible to delete all matrices in the list that contain even a single NA? Once I reduce the matrices to what rows I want, I need to eliminate all matrices that have missing data.

Thank you all for your help!

  • 1
    Just use a anonymous function `lapply(lst, function(x) x[-c(2, 4, 6),])` – akrun Oct 24 '19 at 19:09
  • @M--, I agree. I consulted that one, and used the answer in my question, but my confusion with basic syntax led me to ask for more clarification. – bobbytreefish Oct 24 '19 at 19:32
  • Welcome to SO. No worries. We just do some moderation to keep the community accessible. Hope to see you around, possibly soon answering questions. Cheers. – M-- Oct 24 '19 at 19:34

1 Answers1

2

We need a , at the end

out1 <- lapply(lst, `[`, -c(2, 4, 6), )

Or to be more clear, an anonymous function would be better

out2 <- lapply(lst, function(x) x[-c(2, 4, 6),])

identical(out1, out2)
#[1] TRUE

data

set.seed(24)
lst <- list(matrix(rnorm(30), 6, 5), matrix(rnorm(30), 6, 5))
akrun
  • 874,273
  • 37
  • 540
  • 662