zorian15
zorian15

Reputation: 55

How to group consecutive integers together from a string in R?

So let's say I have this string

x <- "1:A 2:A 3:A 5:A 7:A 8:A 9:A"

Is there a function in R that allows me to prepare the parts of this string so it would output:

[1] 1-3:A 5:A 7-9:A

Upvotes: 3

Views: 190

Answers (2)

d.b
d.b

Reputation: 32548

#Get the numeric values only
temp = as.integer(unlist(strsplit(gsub(":A", "", x), " ")))

#Split temp into chunks of consecutive integers
#Get range for each chunk and paste them together
#Paste :A at the end
sapply(split(temp, cumsum(c(TRUE, diff(temp) != 1))), function(x)
    paste(paste(unique(range(x)), collapse = "-"), ":A", sep = ""))
#      1       2       3 
#"1-3:A"   "5:A" "7-9:A" 

Upvotes: 3

Matt
Matt

Reputation: 994

strsplit() will turn the string into a vector of characters:

> x=strsplit(x, split=" ")[[1]]
[1] "1:A" "2:A" "3:A" "5:A" "7:A" "8:A" "9:A"

From there, you can get the raw numbers as characters:

> x=gsub(":A", "", x)
[1] "1" "2" "3" "5" "7" "8" "9"

Then you can convert to numbers and subset them however you want.

Upvotes: 0

Related Questions