Peter Keller
Peter Keller

Reputation: 31

How to split a string before the delimiter?

I have a character string like the below.

a <- "T,2016,07,T,2016,07,22,T,2016,07"

I would like to split it to get this,

b <- c("T,2016,07", "T,2016,07", "T,2016,07")

Could you tell me the way? Many thanks.

Upvotes: 1

Views: 121

Answers (3)

akuiper
akuiper

Reputation: 215117

Or use regular expression to split:

strsplit(a, ",(?=T)", perl = T)
# [[1]]
# [1] "T,2016,07"    "T,2016,07,22" "T,2016,07"

Upvotes: 7

Robert Hijmans
Robert Hijmans

Reputation: 47601

You can do

x <- gsub("T", "%T", a)
y <- unlist(strsplit(x, "%"))[-1]

Upvotes: 3

r2evans
r2evans

Reputation: 160952

a <- "T,2016,07,T,2016,07,22,T,2016,07"
paste0("T", Filter(nzchar, strsplit(a, ",?T")[[1]]))
# [1] "T,2016,07"    "T,2016,07,22" "T,2016,07"   

Upvotes: 2

Related Questions