schlusie
schlusie

Reputation: 2017

replace number with correct number of digits in r

In R I have following vector and I'm trying to get following result:

vec <- c("6-9 h", "9-13 h", "13-16 h", "16-18 h")
res <- c("06:00-09:00", "09:00-13:00", "13:00-16:00", "16:00-18:00")

My approach using the gsub function works partially

gsub("(.*)-(.*) (.*)", "\\1:00-\\2:00", vec)
# result:
"6:00-9:00"   "9:00-13:00"  "13:00-16:00" "16:00-18:00"

Now my question: Is there a way to input the zeros for single digit numbers with regexpression?

Upvotes: 2

Views: 808

Answers (2)

lukeA
lukeA

Reputation: 54287

Here's a sprintf approach:

sapply(regmatches(vec, gregexpr("\\d+", vec)), function(x) { 
  x <- as.numeric(x)
  sprintf("%02d:00-%02d:00", x[1], x[2])
}) 
# [1] "06:00-09:00" "09:00-13:00" "13:00-16:00" "16:00-18:00"

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174874

You need to use one more gsub function.

> vec <- c("6-9 h", "9-13 h", "13-16 h", "16-18 h")
> m <- gsub("(.*)-(.*) (.*)", "\\1:00-\\2:00", vec)
> gsub("\\b(\\d):", "0\\1:", m)
[1] "06:00-09:00" "09:00-13:00" "13:00-16:00" "16:00-18:00"

\\b(\\d): matches the number which has exactly one digit. \b matches between a word character and a non-word character.

Upvotes: 4

Related Questions