Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Removing blanks from the list

Tags:

r

I'm wondering if there is any way to remove blanks from the list. As far as I've searched, I found out that there are many Q&As for removing the whole element from the list, but couldn't find the one regarding a specific component of the element.

To be specific, the list now I'm working with looks like this:

[[1]]
[1] "1" ""  ""  "2" ""  ""  "3"

[[2]]
[1] "weak"

[[3]]
[1] "22" "33"

[[4]]
[1] "44"  "34p" "45" 

From above, you can find " ", which should be removed. I've tried different commands like

text.words.bl <- text.words.ll[-which(text.words.ll==" ")]
text.words.bl <- text.words.ll[!sapply(text.words.ll, is.null)]

etc, but seems like " "s in [[1]] of the list still remains.

Is it impossible to apply commands to small pieces in each element of the list? (e.g. 1, 2, weak, 22, 33... respectively)

I've used "lapply" function to run specific commands to each elements, and it seemed like those lapply commands all worked....

JY

like image 897
prejay10 Avatar asked Oct 15 '25 06:10

prejay10


1 Answers

Use %in%, but negate it with !:

## Sample data:
L <- list(c(1, 2, "", "", 4), c(1, "", "", 2), c("", "", 3))
L
# [[1]]
# [1] "1" "2" ""  ""  "4"
# 
# [[2]]
# [1] "1" ""  ""  "2"
# 
# [[3]]
# [1] ""  ""  "3"

The replacement:

lapply(L, function(x) x[!x %in% ""])
# [[1]]
# [1] "1" "2" "4"
# 
# [[2]]
# [1] "1" "2"
# 
# [[3]]
# [1] "3"

Obviously, assign the output to "L" if you want to overwrite the original dataset:

L[] <- lapply(L, function(x) x[!x %in% ""])
like image 156
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 18 '25 03:10

A5C1D2H2I1M1N2O1R2T1