我的数据框并不是真正的“长格式”,而是比我想要的更长的格式。我想将其压缩为一种“宽形式”,该形式将与ID相关联的所有信息合并为一行。现在,某些信息会在每行上重复(例如下面的示例中的日期),合并行时需要保留其他信息(例如下面的类型列)。谢谢!
id <- c(1000, 1000, 1000, 1001, 1001, 1001)
type <- c("A", "B", "B", "C", "C", "A")
dates <- c("10/5/2019", "10/5/2019", "10/5/2019", "9/17/2020", "9/17/2020", "9/17/2020")
df <- as.data.frame(cbind(id, type, dates))
df
id type dates
1 1000 A 10/5/2019
2 1000 B 10/5/2019
3 1000 B 10/5/2019
4 1001 C 9/17/2020
5 1001 C 9/17/2020
6 1001 A 9/17/2020
我希望它看起来像这样:
另一种选择仅使用tidyverse
:
library(tidyverse)
#Code
df %>% group_by(id) %>% mutate(idv=paste0('type.',1:n())) %>%
pivot_wider(names_from = idv,values_from=type)
输出:
# A tibble: 2 x 5
# Groups: id [2]
id dates type.1 type.2 type.3
<chr> <chr> <chr> <chr> <chr>
1 1000 10/5/2019 A B B
2 1001 9/17/2020 C C A
或使用row_number()
(@ r2evans的积分):
#Code 2
df %>% group_by(id) %>% mutate(idv=paste0('type.',row_number())) %>%
pivot_wider(names_from = idv,values_from=type)
输出:
# A tibble: 2 x 5
# Groups: id [2]
id dates type.1 type.2 type.3
<chr> <chr> <chr> <chr> <chr>
1 1000 10/5/2019 A B B
2 1001 9/17/2020 C C A
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句