This may sound a very beginner's question and very well it could also be a very basic and stupid question, but somehow I am having headache in doing it.
Let's suppose I have a single item list
v <- as.list("1, 2, 3,")
v
[[1]]
[1] "1, 2, 3,"
Now I want to split all of its items as separate items
v2 <- lapply(str_split(v, pattern = ","), trimws)
v2
[[1]]
[1] "1" "2" "3" ""
Now I want to remove this ""
from the first and only item of this list without using []
?
Using nzchar
.
lapply(v2, function(x) x[nzchar(x)])
# [[1]]
# [1] "1" "2" "3"
Or use base::strsplit
in the first place which appears to be more sophisticated.
lapply(strsplit(v[[1]], ","), trimws)
# [[1]]
# [1] "1" "2" "3"
You can use Filter
with nchar
v2 <- lapply(str_split(v, pattern = ",\\s?"), Filter, f = nchar)
which gives
> v2
[[1]]
[1] "1" "2" "3"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With