简体   繁体   中英

Using lapply to subset a list of character lists in R

I have the following line that subsets a character list correctly:

> cpc_data2[[1]]
 [1] ""     "Week" ""     ""     ""     ""     ""     ""     ""     ""    
[11] ""     "SST"  "SSTA" ""     ""     ""     ""     "SST"  "SSTA" ""    
[21] ""     ""     ""     "SST"  "SSTA" ""     ""     ""     ""     "SST" 
[31] "SSTA"
> cpc_data2[[1]][which(cpc_data2[1][[1]] != "")]
[1] "Week" "SST"  "SSTA" "SST"  "SSTA" "SST"  "SSTA" "SST"  "SSTA"

I would like to subset every list in cpc_data2 . How should I do this? I have tried the following, clearly my syntax is incorrect:

> cpc_data3 = lapply(cpc_data2, function(x) x[which(x[[1]] != "")])
> head(cpc_data3)
[[1]]
character(0)

[[2]]
character(0)

[[3]]
character(0)

你可以试试

lapply(cpc_data2, function(x) x[x!=''])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM