1

I have a list of my.list that looks like this

$S1

        A     B     C         D
1  101027    NA  0.48        NA
2  101031  1.50  1.30 0.8666667
3  101032  1.40  0.78 0.5571429
4  101127    NA    NA        NA
5  101220  9.30  7.30 0.7849462

$S2

        A     B     C         D
1  102142    NA  0.45        NA
2  102143  0.70  1.20 1.7142857
3  102144    NA  0.44        NA
4  102148  0.45    NA        NA
5  102151  0.91  0.64 0.7032967
6  102152  0.78    NA        NA

I would like to remove any rows that have NA from the data frame of the list so it looks like

$S1

        A     B     C         D
2  101031  1.50  1.30 0.8666667
3  101032  1.40  0.78 0.5571429
5  101220  9.30  7.30 0.7849462

$S2

        A     B     C         D
2  102143  0.70  1.20 1.7142857
5  102151  0.91  0.64 0.7032967

I tried

mod_my.list = my.list[!sapply(my.list, is.na)]

and it didn't work. Could anyone help? Thanks!

Reproducible data:

my.list <- structure(list(S1 = structure(list(A = c(101027L, 101031L, 101032L, 
101127L, 101220L), B = c(NA, 1.5, 1.4, NA, 9.3), C = c(0.48, 
1.3, 0.78, NA, 7.3), D = c(NA, 0.8666667, 0.5571429, NA, 0.7849462
)), .Names = c("A", "B", "C", "D"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5")), S2 = structure(list(A = c(102142L, 102143L, 
102144L, 102148L, 102151L, 102152L), B = c(NA, 0.7, NA, 0.45, 
0.91, 0.78), C = c(0.45, 1.2, 0.44, NA, 0.64, NA), D = c(NA, 
1.7142857, NA, NA, 0.7032967, NA)), .Names = c("A", "B", "C", 
"D"), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5", "6"))), .Names = c("S1", "S2"))
Rich Scriven
  • 90,041
  • 10
  • 148
  • 213
kin182
  • 329
  • 4
  • 12
  • `lapply(my.list, function(x) x[complete.cases(x),])`. Basically take any answer from [here](https://stackoverflow.com/questions/4862178/remove-rows-with-nas-missing-values-in-data-frame) and `lapply` it over your list. – Ronak Shah Oct 13 '17 at 02:03

1 Answers1

6

na.omit() can be used on data frames to remove any rows that contain NA values. We can use lapply() to apply it over my.list.

lapply(my.list, na.omit)
# $S1
#        A   B    C         D
# 2 101031 1.5 1.30 0.8666667
# 3 101032 1.4 0.78 0.5571429
# 5 101220 9.3 7.30 0.7849462
#
# $S2
#        A    B    C         D
# 2 102143 0.70 1.20 1.7142857
# 5 102151 0.91 0.64 0.7032967
Rich Scriven
  • 90,041
  • 10
  • 148
  • 213