Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R : Split a String into Vector & remove Empty stirngs

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

Try

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

[[1]]
[1] "item1" "map"   "item2"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading