如何从列表的数据框中删除NA?

时间:2017-10-13 01:50:07

标签: r list dataframe

我有一个my.list的列表,看起来像这样

$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

我想从列表的数据框中删除任何包含NA的行,使其看起来像

$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

我试过

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

它并没有奏效。有人可以帮忙吗?谢谢!

可重复数据:

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"))

1 个答案:

答案 0 :(得分:4)

na.omit()可用于数据框,以删除包含NA值的所有行。我们可以使用lapply()将其应用于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