4

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))
user3375672
  • 3,728
  • 9
  • 41
  • 70
  • 1
    You can add a `,` at the end of `x` when no comma ending the string but not really efficient, use `stringr` – Clemsang Oct 01 '19 at 14:47

2 Answers2

1

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")
MatthewR
  • 2,660
  • 5
  • 26
  • 37
-1
strmagic <- function(x) unlist(strsplit(sub(",$", ",,", x), split = ","))

strsplit does not recognize the "empty" last element. sub(",$", ",,", x) appends an additional comma to x if the last character in x is a comma, solving the problem.

Mikael Jagan
  • 9,012
  • 2
  • 17
  • 48
  • 3
    Do not post an answer with merely codes. While your solution can be useful, you should also explain why the code will fix the problem that was described in the question. – 4b0 Dec 02 '22 at 03:42