简体   繁体   中英

How to convert a column of date string to dates in R

I have a csv file that I use read.csv to read in as so

ff = read.csv('ff5.csv',  col.names = c('date','mkt', 'smb','hml','rmw','cma','rf'), colClasses = c('character',rep('numeric',6)))

The date column is in the form of '197007'. It only gives the year and month, so I resort to as.yearmon in zoo package to convert the date column as so

as.Date(as.yearmon(date,'%Y%m'))

Now for each entry in the date column, it works. But when I try to assign it back to the column entry like so, it gives me numbers in character!

library(zoo)

ff = read.csv('ff5.csv',  col.names = c('date','mkt', 'smb','hml','rmw','cma','rf'), colClasses = c('character',rep('numeric',6)))

for (i in 1:length(ff$date)){
  date = ff$date[i]
  d = as.Date(as.yearmon(as.character(date),'%Y%m'))
  ff$date[i] = d
}

How should I solve this? Data can be downloaded here

http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Research_Data_5_Factors_2x3_CSV.zip

No need to use a loop.

txt <- "197007
198511
201512"

library(zoo)
ff <- read.table(text=txt, col.names = "date")
ff$date <- as.Date(as.yearmon(as.character(ff$date), "%Y%m"))

str(ff)
'data.frame':   3 obs. of  1 variable:
 $ date: Date, format: "1970-07-01" "1985-11-01" ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM