Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an unnamed element from a single item list?

Tags:

string

list

r

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 []?

like image 521
AnilGoyal Avatar asked Dec 22 '20 11:12

AnilGoyal


2 Answers

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"
like image 166
jay.sf Avatar answered Sep 18 '22 02:09

jay.sf


You can use Filter with nchar

v2 <- lapply(str_split(v, pattern = ",\\s?"), Filter, f = nchar)

which gives

> v2
[[1]]
[1] "1" "2" "3"
like image 35
ThomasIsCoding Avatar answered Sep 22 '22 02:09

ThomasIsCoding