Error in if (nchar(i) == 10) { : the condition has length > 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}
  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)}

>Solution :

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"

Leave a ReplyCancel reply