Home > database >  Insert specific numbers at the end of the values of a column in R
Insert specific numbers at the end of the values of a column in R

Time:07-16

Let's say I have a data df like this:

df<-data.frame(date=c(202203,202204,202205,202206))

202203 means March, 2022. So all the values of date column represent year and month . However, since I don't know the exact date, I want to insert 01 to every values of date column.That is ,202203should be 20220301:March 1st,2022 . My expected output is

df<-data.frame(date=c(20220301,20220401,20220501,20220601))

I tried to use gsub but, the output was not what I have expected.

CodePudding user response:

df$date <- as.numeric(paste0(df$date, "01"))

oh hang on, got a better one:

df$date <- df$date * 100   1

CodePudding user response:

You should use paste0 and loop.

For example:

    for(i in df$date){
    
    paste0(i, "01") -> df$date

}

  • Related