1

I want to change the time format, which I have as column ("Date") in my data frame ("data"). It is imported from a csv as -Q1 1990- and I would like to have it as -1990Q1-, but my function is not perfect. I tried:

  for (i in 1:length(data$Date)){
    data$Date[i] <- paste(substr(data$Date[i], 4,8),substr(data$Date[i], 1,2),
    sep="")
    }

The result is a column in which each row has a NA and I do not know why. Can someone help? I found already the thread Extracting the last n characters from a string in R. In that threat they only mentioned the problem, but did not solve it in an understandable way for me.

Thanks in advance

Community
  • 1
  • 1
René
  • 79
  • 8
  • You have probably checked this: but just in case what is class(data$Date)? – mcheema Apr 19 '15 at 23:11
  • In the cells are factors. – René Apr 20 '15 at 11:38
  • then just use data$Date <- as.character(data$Date) to change to strings. You can change back if needed. I think you will need to tweak your substring calls but I am sure you can do that once you get visual feedback of the result of the paste command. – mcheema Apr 20 '15 at 12:15

1 Answers1

1

You can try the following:

data$Date <- sub('-(\\w+) *(\\d{4})-', '-\\2\\1-', data$Date)
hwnd
  • 69,796
  • 4
  • 95
  • 132