简体   繁体   English

如何将数据框中的日期列转换为R中的日期

[英]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. 因此,这是一列日期,我想将其转换为R中的日期。它是一个儒略日期,其中前4位数字表示年份,后三位是该年第一天的天数。 There are numerous 0's , and the system will output that if there is no date associated. 有多个0,如果没有关联的日期,系统将输出。 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. 我尝试使用lapply,但是每次尝试将列表转换为数据框时,都会得到随机整数。 Any help would be great thanks! 任何帮助将非常感谢!

在此处输入图片说明

sapply (or unlisting the result from lapply) converts your dates to numeric values. sapply(或从lapply中取消列出结果)会将日期转换为数值。 If your column is called df$date , you could to the following: 如果您的列名为df$date ,则可以执行以下操作:

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

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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