r-如何将一个日期列转换为三个单独的列(y,m,d)



我有一个大型数据集,其中包含数千个ymd格式的日期。我想转换这个列,这样按年、月和日有三个单独的列。实际上有成千上万的日期,所以我试图用整个数据集的一个代码来实现这一点。

您可以使用lubridate中的year()month()day()提取器。这里有一个例子:

library('dplyr')
library('tibble')
library('lubridate')
## create some data
df <- tibble(date = seq(ymd(20190101), ymd(20191231), by = '7 days'))

产生

> df
# A tibble: 53 x 1
date      
<date>    
1 2019-01-01
2 2019-01-08
3 2019-01-15
4 2019-01-22
5 2019-01-29
6 2019-02-05
7 2019-02-12
8 2019-02-19
9 2019-02-26
10 2019-03-05
# … with 43 more rows

然后mutatedf使用相关的提取器函数:

df <- mutate(df,
year  = year(date),
month = month(date),
day   = day(date))

这导致:

> df
# A tibble: 53 x 4
date        year month   day
<date>     <dbl> <dbl> <int>
1 2019-01-01  2019     1     1
2 2019-01-08  2019     1     8
3 2019-01-15  2019     1    15
4 2019-01-22  2019     1    22
5 2019-01-29  2019     1    29
6 2019-02-05  2019     2     5
7 2019-02-12  2019     2    12
8 2019-02-19  2019     2    19
9 2019-02-26  2019     2    26
10 2019-03-05  2019     3     5
# … with 43 more rows

如果只需要新的三列,请使用transmute()而不是mutate()

使用lubridate但不必指定分隔符:

library(tidyverse)
df <- tibble(d = c('2019/3/18','2018/10/29'))
df %>%
mutate(
date = lubridate::ymd(d),
year = lubridate::year(date),
month = lubridate::month(date),
day = lubridate::day(date)
)

请注意,您可以将第一个条目从ymd更改为适合其他格式。

需要较少代码的tidyverse解决方案可能略有不同:

代码

tibble(date = "2018-05-01") %>% 
mutate_at(vars(date), lst(year, month, day))

结果

# A tibble: 1 x 4
date        year month   day
<chr>      <dbl> <dbl> <int>
1 2018-05-01  2018     5     1
#Data
d = data.frame(date = c("2019-01-01", "2019-02-01", "2012/03/04"))
library(lubridate)    
cbind(d,
read.table(header = FALSE,
sep = "-",
text = as.character(ymd(d$date))))
#        date   V1 V2 V3
#1 2019-01-01 2019  1  1
#2 2019-02-01 2019  2  1
#3 2012/03/04 2012  3  4

library(dplyr)
library(tidyr)
library(lubridate)
d %>%
mutate(date2 = as.character(ymd(date))) %>%
separate(date2, c("year", "month", "day"), "-")
#        date year month day
#1 2019-01-01 2019    01  01
#2 2019-02-01 2019    02  01
#3 2012/03/04 2012    03  04

最新更新