如何从 3 个不同的向量(日、月、年)创建 "as.Date" 的日期?
How to create a date with "as.Date" from 3 different vectors (day, month, years)?
我有 3 个不同的向量,包括日、月和年的数据。我想将这 3 个合并为一个并将其添加到我的数据框的新列中。我尝试使用“as.Date”来合并这 3 个向量,但它不起作用...
你能帮帮我吗? :)
这是我的代码:
Day<- substr(x = my_meteo_charleroi$Local.Time, start = 1, stop =2 )
Month<- substr(x = my_meteo_charleroi$Local.Time, start = 4, stop =5 )
Year<- substr(x = my_meteo_charleroi$Local.Time, start = 7, stop =10 )
my_date<- as.Date(c(Day, Month, Year), format = c("%d, %m, %y"))
这个有用吗:
Day <- c(10,11,12)
Month <- c(11,11,12)
Year <- c(2019,2020,2020)
library(tibble)
library(dplyr)
tibble(Day, Month, Year) %>%
mutate(my_date = paste(Day, Month, Year, sep = '-')) %>%
mutate(my_date = as.Date(my_date, format = '%d-%m-%Y', origin = '1970-01-01')) %>%
pull(my_date)
[1] "2019-11-10" "2020-11-11" "2020-12-12"
具有 my_date 列的数据框如下所示:
tibble(Day, Month, Year) %>% mutate(my_date = paste(Day, Month, Year, sep = '-')) %>%
mutate(my_date = as.Date(my_date, format = '%d-%m-%Y', origin = '1970-01-01'))
# A tibble: 3 x 4
Day Month Year my_date
<dbl> <dbl> <dbl> <date>
1 10 11 2019 2019-11-10
2 11 11 2020 2020-11-11
3 12 12 2020 2020-12-12
你已经很接近了,只需要修改两处。
as.Date()
的两个参数在这里都应该是字符串,而不是向量。
as.Date(paste(Day, Month, Year, sep = "-"), format = '%d-%m-%y')
我有 3 个不同的向量,包括日、月和年的数据。我想将这 3 个合并为一个并将其添加到我的数据框的新列中。我尝试使用“as.Date”来合并这 3 个向量,但它不起作用...
你能帮帮我吗? :)
这是我的代码:
Day<- substr(x = my_meteo_charleroi$Local.Time, start = 1, stop =2 )
Month<- substr(x = my_meteo_charleroi$Local.Time, start = 4, stop =5 )
Year<- substr(x = my_meteo_charleroi$Local.Time, start = 7, stop =10 )
my_date<- as.Date(c(Day, Month, Year), format = c("%d, %m, %y"))
这个有用吗:
Day <- c(10,11,12)
Month <- c(11,11,12)
Year <- c(2019,2020,2020)
library(tibble)
library(dplyr)
tibble(Day, Month, Year) %>%
mutate(my_date = paste(Day, Month, Year, sep = '-')) %>%
mutate(my_date = as.Date(my_date, format = '%d-%m-%Y', origin = '1970-01-01')) %>%
pull(my_date)
[1] "2019-11-10" "2020-11-11" "2020-12-12"
具有 my_date 列的数据框如下所示:
tibble(Day, Month, Year) %>% mutate(my_date = paste(Day, Month, Year, sep = '-')) %>%
mutate(my_date = as.Date(my_date, format = '%d-%m-%Y', origin = '1970-01-01'))
# A tibble: 3 x 4
Day Month Year my_date
<dbl> <dbl> <dbl> <date>
1 10 11 2019 2019-11-10
2 11 11 2020 2020-11-11
3 12 12 2020 2020-12-12
你已经很接近了,只需要修改两处。
as.Date()
的两个参数在这里都应该是字符串,而不是向量。
as.Date(paste(Day, Month, Year, sep = "-"), format = '%d-%m-%y')