Home > OS >  R : Split a String into Vector & remove Empty strings
R : Split a String into Vector & remove Empty strings

Time:06-24

I would like to take a string of the following form and make it into a string vector. The following does not work, and I can't follow the docs to figure it out:

params <- "-item1-map-item2-"
param_list <- as.list(strsplit(params, "-")[1])
print(param_list[1])
[[1]]
[1] ""      "item1" "map"   "item2"

There is an annoying empty string at the start. I've tried to use

param_list <- stringi::stri_remove_empty_na(param_list)

but that throws an error:

> Warning message: In stri_enc_toutf8(x) : argument is not an atomic
> vector; coercing

Another suggested :

param_list <- param_list[nzchar(param_list) & complete.cases(param_list)]
print(param_list[1])
[[1]]
[1] ""      "item1" "map"   "item2"

But no change... Could anyone shine a little light on this?

CodePudding user response:

Try

lapply(param_list, function(x) {x[x != ""]})

[[1]]
[1] "item1" "map"   "item2"
  •  Tags:  
  • r
  • Related