Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove blanks from strsplit in R

Tags:

r

> dc1
  V1                V2
1 20140211-0100     |Box
2 20140211-1782     |Office|Ball
3 20140211-1783     |Office
4 20140211-1784     |Office
5 20140221-0756     |Box
6 20140203-0418     |Box
> strsplit(as.character(dc1[,2]),"^\\|")
[[1]]
[1] ""    "Box"


[[2]]
[1] ""             "Office" "Ball"


[[3]]
[1] ""             "Office"


[[4]]
[1] ""             "Office"


[[5]]
[1] ""    "Box"


[[6]]
[1] ""    "Box"  

How do i remove the blank ("") from strsplit results.The result should look like:

[[1]]
[1] "Box"
[[2]]
[1] "Office"    "Ball"
like image 219
Prasanna Nandakumar Avatar asked Jun 12 '14 07:06

Prasanna Nandakumar


1 Answers

You can check use lapply on your list. I changed the definition of your strsplit to match your intended output.

dc1 <- read.table(text = 'V1                V2
1 20140211-0100     |Box
2 20140211-1782     |Office|Ball
3 20140211-1783     |Office
4 20140211-1784     |Office
5 20140221-0756     |Box
6 20140203-0418     |Box', header = TRUE)

out <- strsplit(as.character(dc1[,2]),"\\|")

> lapply(out, function(x){x[!x ==""]})
[[1]]
[1] "Box"

[[2]]
[1] "Office" "Ball"  

[[3]]
[1] "Office"

[[4]]
[1] "Office"

[[5]]
[1] "Box"

[[6]]
[1] "Box"
like image 167
jdharrison Avatar answered Sep 18 '22 17:09

jdharrison