当我试图在DF中存储日期时,它被表示为数字而不是数据格式。下面是我的例子。
library(lubridate)
df1 = data.frame(task = c('do somthing', 'do something else', 'do something more')
,Start_date = c(NA, NA, NA))
Start_date = ymd("2023-12-01")
df1$Date_Start[1] = Start_date
Start_date #this returns a "2023-12-01"
df1$Date_Start[1] #this returns a 19692
我想让df1$Date_Start[1]存储"2023-12-01">
这与lubridate
无关,因为您将在as.Date
中获得与lubridate::ymd
相同的结果。
当您创建一个NA值的列,但您计划将日期写入其中时,您需要告诉R您打算通过使用as.Date(NA)
填充该列来将其用于日期。否则,R会将日期转换为数值。
library(lubridate)
df1 = data.frame(task = c('do somthing', 'do something else', 'do something more')
,Date_Start = c(NA, NA, NA))
Start_date = ymd("2023-12-01")
df1$Date_Start <- as.Date(NA)
df1$Date_Start[1] <- Start_date[1]
Start_date
#> [1] "2023-12-01"
df1$Date_Start[1]
#> [1] "2023-12-01"
df1
#> task Date_Start
#> 1 do somthing 2023-12-01
#> 2 do something else <NA>
#> 3 do something more <NA>
创建于2022-12-29与reprex v2.0.2
Start_date
变量被创建为逻辑对象:
str(df1)
'data.frame': 3 obs. of 2 variables:
$ task : chr "do somthing" "do something else" "do something more"
$ Start_date: logi NA NA NA
在第一个元素定义日期后,对象被转换为数字
str(df1)
'data.frame': 3 obs. of 2 variables:
$ task : chr "do somthing" "do something else" "do something more"
$ Start_date: num 19692 NA NA
您可以通过将Start_date
变量的类型定义为Date对象来创建data.frame。
df1 = data.frame(task = c('do somthing', 'do something else', 'do something more'), Start_date = as.Date(NA))
str(df1)
'data.frame': 3 obs. of 2 variables:
$ task : chr "do somthing" "do something else" "do something more"
$ Start_date: Date, format: NA NA NA
现在可以在第一个元素中定义日期:
df1$Start_date[1] = Start_date
df1
task Start_date
1 do somthing 2023-12-01
2 do something else <NA>
3 do something more <NA>
您可以直接指定您的日期格式:
library(lubridate)
df1 = data.frame(task = c('do somthing', 'do something else', 'do something more')
,Start_date = c(NA, NA, NA))
df1$Start_date[1] <- format(ymd("2023-12-01"), "%Y-%m-%d")