如何从 R 中的列表中删除 NULL 值?


NULL 值用于表示一个对象,特别是长度为零的列表。如果一个列表包含 NULL,那么我们可能希望用另一个值替换它,或者在没有替换项时将其从列表中删除。若要从列表中删除 NULL 值,我们可以使用 sapply 取反,并使用 is.NULL。

示例

 在线演示

x<-list(rep(10,5),NULL,12,"Tutorialspoint",2006,NULL,NULL,NULL,TRUE,c(rep(1,5),rep(2,5),NULL,"Education","Video Lectures","Online",NULL,"Over Million Visitors"))
x
[[1]]
[1] 10 10 10 10 10
[[2]]
NULL
[[3]]
[1] 12
[[4]]
[1] "Tutorialspoint"
[[5]]
[1] 2006
[[6]]
NULL
[[7]]
NULL
[[8]]
NULL
[[9]]
[1] TRUE
[[10]]
[1] "1"      "1"         "1"
[4] "1"      "1"         "2"
[7] "2"      "2"         "2"
[10] "2" "Education" "Video Lectures"
[13] "Online" "Over Million Visitors"
x<-x[!sapply(x,is.null)]
x
[[1]]
[1] 10 10 10 10 10
[[2]]
[1] 12
[[3]]
[1] "Tutorialspoint"
[[4]]
[1] 2006
[[5]]
[1] TRUE
[[6]]
[1]          "1"        "1"    "1"
[4]          "1"        "1"    "2"
[7]          "2"        "2"    "2"
[10] "2" "Education" "Video Lectures"
[13] "Online" "Over Million Visitors"
y<-list(c(5,10,15),NULL,c(rep("A",4)),rep(5,15,10,times=4),c(78,91,56,47,58,26,36,74,84),NULL,NULL,NULL)
y
[[1]]
[1] 5 10 15
[[2]]
NULL
[[3]]
[1] "A" "A" "A" "A"
[[4]]
[1] 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
[[5]]
[1] 78 91 56 47 58 26 36 74 84
[[6]]
NULL
[[7]]
NULL
[[8]]
NULL
y<-y[!sapply(y,is.null)]
y
[[1]]
[1] 5 10 15
[[2]]
[1] "A" "A" "A" "A"
[[3]]
[1] 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
[[4]]
[1] 78 91 56 47 58 26 36 74 84

更新于: 2020 年 8 月 21 日

5K+ 次浏览

启动您的事业

完成课程后获得认证

开始
广告