0

Here I have a chr column data$month which initially was like this "1980m10". I'm trying to convert it into a date format so I can plot line graph for stock returns. however when I try

as.Date(data$month, "%Ym%m") 

it returns me only NA values.

I have tried to convert the column into more clear format

data$year = substr(data$month,1,4)
data$mon = substr(data$month,6,8)

library(stringr)

data$month = paste(data$year,'-',data$mon)

as.Date(data$month, "%y - %m")

However still it returns me only NA values. Idk how to solve this problem. I have tried without format: but it says the character string is not in a standard unambiguous format

Amirgiano
  • 69
  • 6

2 Answers2

1

You could try adding a default day to the date, e.g. 01, to make it a formal date:

data$year <- substr(data$month, 1, 4)
data$mon <- substr(data$month, 6, 8)
data$date <- as.Date(paste(data$year, data$mon, "01", sep="-"))
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Take a look at the package ?stringr containing the str_sub function

R> str_sub(data$month,1,4) 
[1] "1980"

Another potential package is the ?substr package. Just take a look at both. As your format is ambiguous I would propose to use a function that simply takes the first 4 characters.

Kylian
  • 319
  • 2
  • 14