简体   繁体   中英

formatting week.year in data frames to have starting zero in R

I have a list of data frames where each data frame contains a date in the format week.year like 01.2019, 02.2019 and so on. I would like to retain the 0 in front of single digit weeks like 01 or 02 as right now it is changing it to 1,2 and so on. I have written the following code which works perfectly where the dataset$CAL column has the week.year values.

X <-list()
x <- nchar(dataset$CAL)
counter=1
for (i in x) {

  if (i==6){
    dataset$CAL[counter]<- paste0("0", dataset$CAL[counter])
  } 
  else {
    dataset$CAL[counter]<-dataset$CAL[counter]
  }
  counter <- counter+1
}

But this has a serious performance issue takes too long to load and also of course using for loop in R not recommended. I tried using lapply function but it is not giving appropriate results

dataset$CAL <- lapply(dataset$CAL, function(x) if (nchar(dataset$CAL)==6) {paste0("0", dataset$CAL)} else {dataset$CAL})

Any pointers in this direction?? Really appreciate the Help.

I think sprintf would solve the problem:

dataset$CAL2 <- sprintf("%06s", dataset$CAL)

Or using str_pad from stringr .

dataset$CAL2 <- stringr::str_pad(dataset$CAL, 6, pad = "0")

We can use sprintf with mutate

library(dplyr)
dataset %>%
  mutate(CAL2 = sprintf("%06s", CAL))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM