1

I want to make a function that runs through a column of dates (data type is characters) and check whether or not it is 10 characters long. If it is, then I want to retain the characters and put it into an element for later use in my other functions. If it is not 10 characters long I would like to insert "0" at position 5 of the string. The characters are dates (e.g. "2016/7/23" and "2016/11/23"). If it is "2016/11/23" I want to keep this the same (this is 10 characters long). If it is "2016/7/23" (this is 9 characters long) I want to add a "0" at position 5 to make it "2016/07/23".

If it does, I want to put the character in "new", if it does not equal 10 characters then I want it to add a "0" into the string at position 5 of the string, then put it into "new". I am running into the problem [Error in if (nchar(i) == 10) { : the condition has length > 1] and I am not sure what I am doing wrong.

for (i in cvdcounttwo_1c_fix){
  if (nchar(i) == 10) {new <- i}
  else{
  nxew <- sub("(.{5})(.*)", "\\10\\2", i)}}

Without the if statement this works, but this adds a 0 at position 5 of the string regardless of the string length.

for (i in cvdcounttwo_1c_fix){ new <- sub("(.{5})(.*)", "\\10\\2", i)}

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • 1
    Could you edit your question to make this reproducible (i.e., example data)? Some tips on how to do that can be found [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?noredirect=1&lq=1) – jpsmith May 02 '23 at 09:13
  • There is no need to prefix, we can convert both strings: with leading zero and without leading zero, with the same format `%m`. Try this example: `as.Date(c("2016/11/23", "2016/7/23"), "%Y/%m/%d")` – zx8754 May 02 '23 at 09:22
  • Possible duplicate https://stackoverflow.com/q/9119180/680068 – zx8754 May 02 '23 at 09:23

1 Answers1

0

This will be easier if you take advantage of R's Date format. I would convert the strings to Date format using as.Date(), specifying what notation is being used. This will add a leading zero to any of the months or days that have only one digit. Then you can use format() to convert the dates back to strings printed in any notation you want.

date_strings <- c("2016/7/23", "2016/11/23")

dates <- as.Date(date_strings, format = '%Y/%m/%d')
# [1] "2016-07-23" "2016-11-23"

format(dates, format = '%Y/%m/%d')
# [1] "2016/07/23" "2016/11/23"
qdread
  • 3,389
  • 19
  • 36