转换为列表时格式化日期

发布于 2025-02-06 22:32:57 字数 1083 浏览 2 评论 0原文

我有这样的桌子:

ID日期状态
1012020-09-141
1022020-09-141
1032020-09-141
1042020-09-142
1052020-09-142
1062020-09-- 142

但想要这样的桌子:

状态ID日期
1101,102,1032020-09-14,2020-09-14,2020-09-14
1104,105,1062020-09-14,2020-09-14,2020-09-14,2020-09-14

我目前正在使用的代码:

注意:日期在运行代码之前以YYYY-MM-DD格式使用。

g1 <- df1 %>% 
  mutate(Date = as.Date(Date, format = '%Y%m%d')) %>%
  group_by(status) %>% 
  summarise_at(c("ID", "Date"), list)

除了新表中的日期不在yyyy-mm-dd中,这似乎有效。例如,2021-06-10正在转换为18788。

I have a table like this:

IDDateStatus
1012020-09-141
1022020-09-141
1032020-09-141
1042020-09-142
1052020-09-142
1062020-09-142

But want a table like this:

StatusIDDate
1101,102,1032020-09-14, 2020-09-14, 2020-09-14
1104,105,1062020-09-14, 2020-09-14, 2020-09-14

Code that i'm currently using:

note: date is in format yyyy-mm-dd before running code.

g1 <- df1 %>% 
  mutate(Date = as.Date(Date, format = '%Y%m%d')) %>%
  group_by(status) %>% 
  summarise_at(c("ID", "Date"), list)

This seems to work except for the date in the new table is not in yyyy-mm-dd. For example, 2021-06-10 is converting to 18788.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陪你搞怪i 2025-02-13 22:32:57

可能的解决方案:

library(tidyverse)

df %>% 
  group_by(Status) %>% 
  summarise(ID = str_c(ID, collapse = ","), Date = str_c(Date, collapse = ","))

#> # A tibble: 2 × 3
#>   Status ID          Date                            
#>    <int> <chr>       <chr>                           
#> 1      1 101,102,103 2020-09-14,2020-09-14,2020-09-14
#> 2      2 104,105,106 2020-09-14,2020-09-14,2020-09-14

一个更简洁的替代方案:

library(tidyverse)

df %>% 
  group_by(Status) %>% 
  summarise(across(c(ID, Date), str_c, collapse = ","))

#> # A tibble: 2 × 3
#>   Status ID          Date                            
#>    <int> <chr>       <chr>                           
#> 1      1 101,102,103 2020-09-14,2020-09-14,2020-09-14
#> 2      2 104,105,106 2020-09-14,2020-09-14,2020-09-14

A possible solution:

library(tidyverse)

df %>% 
  group_by(Status) %>% 
  summarise(ID = str_c(ID, collapse = ","), Date = str_c(Date, collapse = ","))

#> # A tibble: 2 × 3
#>   Status ID          Date                            
#>    <int> <chr>       <chr>                           
#> 1      1 101,102,103 2020-09-14,2020-09-14,2020-09-14
#> 2      2 104,105,106 2020-09-14,2020-09-14,2020-09-14

A more succinct alternative:

library(tidyverse)

df %>% 
  group_by(Status) %>% 
  summarise(across(c(ID, Date), str_c, collapse = ","))

#> # A tibble: 2 × 3
#>   Status ID          Date                            
#>    <int> <chr>       <chr>                           
#> 1      1 101,102,103 2020-09-14,2020-09-14,2020-09-14
#> 2      2 104,105,106 2020-09-14,2020-09-14,2020-09-14
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文