R strsplit keep last empty element as empty string

Viewed 195

R's strsplit drops the last element if "empty" (example 2) but not when occurring first (example 3) or in the middle of the vector to split (example 4).

> unlist(strsplit(x = "1,4", split = ",")) #Example 1
[1] "1" "4"
> unlist(strsplit(x = ",4", split = ",")) #Example 2
[1] ""  "4"
> unlist(strsplit(x = "1,", split = ",")) #Example 3
[1] "1"
> unlist(strsplit(x = "1,,,4", split = ",")) #Example 4
[1] "1" ""  ""  "4"

Is there a way to parse strings that allows keeping the last element if empty after split :

> strmagic(x = "1,", split = ",") #strmagic being the wanted function
[1] "1" ""

A solution with other packages is here (is seems). Can it be done in base R?

UPDATE

Will adding a filler element be necessary ed then a la:

strmagic <- function(v, sep)lapply(v, function(x)head(unlist(strsplit(paste(x, "-", sep = sep), split = sep)), -1))
1 Answers

Weird. This works but is not the most efficient. ZAQ is just a set of random characters

sp <- function( X ){
    X <- paste0( X, "ZAQ" )
    X <- unlist(strsplit(x = X, split = ","))
    X <- gsub( "ZAQ" ,"" ,X) 
    X
}
sp("1,4")
sp(",4")
sp("1,")
sp("1,,,4")
Related