Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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}
  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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading