Home > Mobile >  Replace a long character value
Replace a long character value

Time:09-28

Based on the data and code below how can I replace a long character value to 01/01/2005?

Code data:

df = structure(list(year = c("2005", "2004", "ORIG", "ORIG", "2000-2001", 
"2000-2001"), date = c("#################################################", "01/01/2004", "01/01/2005", "01/01/2005", 
"01/01/2000", "01/01/2000")), class = "data.frame", row.names = c(NA, 
-6L))

desired = structure(list(year = c("2005", "2004", "ORIG", "ORIG", "2000-2001", 
"2000-2001"), date = c("01/01/2005", "01/01/2004", "01/01/2005", "01/01/2005", 
"01/01/2000", "01/01/2000")), class = "data.frame", row.names = c(NA, 
-6L))

# Replace the date value with the long string to `01/01/2005`
# Normally you would do something like this
df = replace(df$date, 1,"01/01/2005")

CodePudding user response:

Create a condition with nchar (number of characters - i.e. if it is greater than 10, replace with '01/01/2005'

library(dplyr)
df <- df %>% 
    mutate(date = replace(date,nchar(date) > 10, "01/01/2005"))

-output

df
  year       date
1      2005 01/01/2005
2      2004 01/01/2004
3      ORIG 01/01/2005
4      ORIG 01/01/2005
5 2000-2001 01/01/2000
6 2000-2001 01/01/2000

Or could be making use of 'year' column

library(stringr)
df %>%
    mutate(date = case_when(nchar(date) > 10 ~
        str_c('01/01/', year), TRUE ~ date))
  year       date
1      2005 01/01/2005
2      2004 01/01/2004
3      ORIG 01/01/2005
4      ORIG 01/01/2005
5 2000-2001 01/01/2000
6 2000-2001 01/01/2000
  • Related