如何從 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+ 次瀏覽

啟動您的事業

完成課程後獲得認證

開始
廣告