pivot_longer 具有多个日期列
pivot_longer with multiple date columns
我有一个包含以下行的数据框:
dt <- data.frame(id = c(1,1), start = as.Date(c("2020-01-01", "2021-02-01")), end = as.Date(c("2020-12-31", "2022-01-31")), cancelled = as.Date(c("2021-01-10", NA)))
dt
## id start end cancelled
## 1 2020-01-01 2020-12-31 2021-01-10
## 1 2021-02-01 2022-01-31 <NA>
我想pivot_longer获得:
id date action
1 2020-01-01 start
1 2020-12-31 end
1 2021-01-10 cancelled
1 2021-02-01 start
1 2022-01-31 end
我认为这会起作用,但它产生了一个错误:
dt %>%
pivot_wider(
cols = !id,
names_to = "date",
values_to = "action")
Error: 2 components of `...` were not used.
We detected these problematic arguments:
* `names_to`
* `values_to`
Did you misspecify an argument?
dt %>% pivot_longer(-id) %>% filter(!is.na(value))
# A tibble: 5 x 3
id name value
<dbl> <chr> <date>
1 1 start 2020-01-01
2 1 end 2020-12-31
3 1 cancelled 2021-01-10
4 1 start 2021-02-01
5 1 end 2022-01-31
我有一个包含以下行的数据框:
dt <- data.frame(id = c(1,1), start = as.Date(c("2020-01-01", "2021-02-01")), end = as.Date(c("2020-12-31", "2022-01-31")), cancelled = as.Date(c("2021-01-10", NA)))
dt
## id start end cancelled
## 1 2020-01-01 2020-12-31 2021-01-10
## 1 2021-02-01 2022-01-31 <NA>
我想pivot_longer获得:
id date action
1 2020-01-01 start
1 2020-12-31 end
1 2021-01-10 cancelled
1 2021-02-01 start
1 2022-01-31 end
我认为这会起作用,但它产生了一个错误:
dt %>%
pivot_wider(
cols = !id,
names_to = "date",
values_to = "action")
Error: 2 components of `...` were not used.
We detected these problematic arguments:
* `names_to`
* `values_to`
Did you misspecify an argument?
dt %>% pivot_longer(-id) %>% filter(!is.na(value))
# A tibble: 5 x 3
id name value
<dbl> <chr> <date>
1 1 start 2020-01-01
2 1 end 2020-12-31
3 1 cancelled 2021-01-10
4 1 start 2021-02-01
5 1 end 2022-01-31