Append a character to a specific location in a column in a data frame

Viewed 73

I am having a data frame like this

df <- data.frame(
       'Week' = c(27,28,29),
       'date' = c("2019-W (01-Jul)","2019-W (08-Jul)","2019-W (15-Jul)"))

I need to append Week column after W in date column

expecteddf <- data.frame(
       'Week' = c(27,28,29),
       'date' = c("2019-W27 (01-Jul)","2019-W28 (08-Jul)","2019-W29 (15-Jul)"))

How can I achieve this in R?

Thanks in advance!!

6 Answers

You can use paste0 with a combination of sub, i.e.

 paste0(sub(' .*', '', df$date), df$Week, sub('.* ', ' ', df$date))
#[1] "2019-W27 (01-Jul)" "2019-W28 (08-Jul)" "2019-W29 (15-Jul)"

in base R, you could also use regmatches + regexpr check the solution @Darren for elaboration on the pattern (?<=W)

regmatches(df$date, regexpr("(?<=W)", df$date, perl = TRUE)) <- df$Week
df
  Week              date
1   27 2019-W27 (01-Jul)
2   28 2019-W28 (08-Jul)
3   29 2019-W29 (15-Jul)

With stringr::str_replace, the replacement can be vectorized:

library(stringr)

df$date = str_replace(df$date, "W", paste0("W", df$Week))
df
#   Week              date
# 1   27 2019-W27 (01-Jul)
# 2   28 2019-W28 (08-Jul)
# 3   29 2019-W29 (15-Jul)

Alternately, we could take a date formatting approach. Converting your date column to an actual Date class (df$Date, below), we can then convert the actual Date to your desired format (or any other).

df$Date = as.Date(df$date, format = "%Y-W (%d-%b)")
df$result = format(df$Date, format = "%Y-W%V (%d-%b)")
df
#   Week            date       Date            result
# 1   27 2019-W (01-Jul) 2019-07-01 2019-W27 (01-Jul)
# 2   28 2019-W (08-Jul) 2019-07-08 2019-W28 (08-Jul)
# 3   29 2019-W (15-Jul) 2019-07-15 2019-W29 (15-Jul)

A base solution with sub(..., perl = T):

within(df, date <- Vectorize(sub)("(?<=W)", Week, date, perl = T))

Note:

  • "(?<=W)" matches the position behind "W".
  • The first two arguments of sub() cannot be vectorized, so Vectorize() or mapply() are needed here.

The corresponding str_replace() version, which is vectorized.

library(dplyr)
library(stringr)

df %>%
  mutate(date = str_replace(date, "(?<=W)", as.character(Week)))

Output

#   Week              date
# 1   27 2019-W27 (01-Jul)
# 2   28 2019-W28 (08-Jul)
# 3   29 2019-W29 (15-Jul)

A base R option using:

  • gsub + Vectorize
expecteddf <- within(df,date <- Vectorize(gsub)("W",paste0("W",Week),date))
  • gsub + mapply
expecteddf <- within(
  df,
  date <- mapply(function(x, p) gsub("(.*W)(\\s.*)", sprintf("\\1%s\\2", p), x), date, Week)
)

You can use mutate in str_c

library(tidyverse)
df %>% 
  mutate(date = str_c(str_sub(date,1,6),
                       Week,
                       str_sub(date,7)))
Related