跨(分解)数据框中的所有日期进行变异
mutate across (decompose) all dates in a dataframe
我的数据框中有很多日期列,需要将所有日期转换为每个日期的三个新列(月、月和年)
我尽量避免专门写下每一列,所以我使用 across
但仍然围绕着这种动词
library(tidyverse)
df <- tibble(dates1 = c("2020-08-03", "2020-08-03"),
dates2 = c("2020-08-05", "2020-08-05"))
df %>% mutate(across(contains("dates"), lubridate::day(.), lubridate::month(.), lubridate::year(.) ))
Error: Problem with `mutate()` input `..1`.
i `..1 = across(...)`.
x do not know how to convert 'x' to class “POSIXlt”
并猜测应该如何命名新列....我有点迷路
在 list
内尝试
library(dplyr)
df %>%
mutate(across(contains("dates"), list(day = ~ lubridate::day(.),
month = ~ lubridate::month(.), year = ~lubridate::year(.) )))
-输出
# A tibble: 2 × 8
dates1 dates2 dates1_day dates1_month dates1_year dates2_day dates2_month dates2_year
<chr> <chr> <int> <dbl> <dbl> <int> <dbl> <dbl>
1 2020-08-03 2020-08-05 3 8 2020 5 8 2020
2 2020-08-03 2020-08-05 3 8 2020 5 8 2020
我的数据框中有很多日期列,需要将所有日期转换为每个日期的三个新列(月、月和年)
我尽量避免专门写下每一列,所以我使用 across
但仍然围绕着这种动词
library(tidyverse)
df <- tibble(dates1 = c("2020-08-03", "2020-08-03"),
dates2 = c("2020-08-05", "2020-08-05"))
df %>% mutate(across(contains("dates"), lubridate::day(.), lubridate::month(.), lubridate::year(.) ))
Error: Problem with `mutate()` input `..1`.
i `..1 = across(...)`.
x do not know how to convert 'x' to class “POSIXlt”
并猜测应该如何命名新列....我有点迷路
在 list
library(dplyr)
df %>%
mutate(across(contains("dates"), list(day = ~ lubridate::day(.),
month = ~ lubridate::month(.), year = ~lubridate::year(.) )))
-输出
# A tibble: 2 × 8
dates1 dates2 dates1_day dates1_month dates1_year dates2_day dates2_month dates2_year
<chr> <chr> <int> <dbl> <dbl> <int> <dbl> <dbl>
1 2020-08-03 2020-08-05 3 8 2020 5 8 2020
2 2020-08-03 2020-08-05 3 8 2020 5 8 2020