简体   繁体   中英

How to convert a column of dates in a dataframe to a Date in R

So here is a column of dates that I want to convert to a Date in R. Its a julian date where the first 4 digits means the year and the last three are the # of days from 1st of that year. There are numerous 0's , and the system will output that if there is no date associated. The function I wrote for it is given below.

   julian=function(x)
      {
      if(x>0)
      {
      x=as.character(x)
      year=substr(x,1,4)
      days=as.integer(substr(x,5,7))-1
      return(as.Date(paste("01/01/",year),format="%m/%d/%Y")+days)
      }
      return(NULL)
  }

I would like to apply this across the column. I tried using lapply but everytime I try to convert the list to a dataframe, I get random integers. Any help would be great thanks!

在此处输入图片说明

sapply (or unlisting the result from lapply) converts your dates to numeric values. If your column is called df$date , you could to the following:

df$new_date <- do.call(c, lapply(df$date,julian))

Hope this helps!

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