我在 R 中有一个列表l,如下所示。我想删除唯一字母数字字符为 0 的元素。我该怎么做?
# Create list
l <- list(c('108', '50', '0]'), c('109','58','0','0]'), c('18','0'))
l
[[1]]
[1] "108" "50" "0]"
[[2]]
[1] "109" "58" "0" "0]"
[[3]]
[1] "18" "0"
# What I want:
l
[[1]]
[1] "108" "50"
[[2]]
[1] "109" "58"
[[3]]
[1] "18"
Run Code Online (Sandbox Code Playgroud)
我们可以使用grepl匹配0或]和否定( )来从元素!中删除值list
lapply(l, function(x) x[!grepl("^0$|\\]", x)])
#[[1]]
#[1] "108" "50"
#[[2]]
#[1] "109" "58"
#[[3]]
#[1] "18"
Run Code Online (Sandbox Code Playgroud)
或者转换为numeric删除NA元素连同0
lapply(l, function(x) x[!is.na(as.numeric(x)) & x != 0])
Run Code Online (Sandbox Code Playgroud)
或者使用setdiff
lapply(l, setdiff, c("0", "0]"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3780 次 |
| 最近记录: |