我有一个有数千行的数据帧,其中有两列我感兴趣的数据: ID和date。有些ID是重复的,但不是日期。我希望每个ID只有一行,然后将不同的日期存储到列中,如: UniqueID、date1、date2等。
有人知道最好的方法是什么吗?我使用R,在R中有什么最好的方法吗?
发布于 2016-09-26 04:30:34
你是说像这样的东西吗?
require(dplyr)
require(tidyr)
dates <- c("02/26/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92")
dat <- data.frame(id = c(1,1,2,3,2), date = as.Date(dates, "%m/%d/%y"))dat如下所示:
id date
1 1 1992-02-26
2 1 1992-02-27
3 2 1992-01-14
4 3 1992-02-28
5 2 1992-02-01使用下面的技巧
dat %>%
select(id, date) %>% #here you select the columns that you want to use
group_by(id) %>%
mutate(seq = paste0("date", row_number(id))) %>%
spread(seq, date)变成这样:
Source: local data frame [3 x 3]
Groups: id [3]
id date1 date2
* <dbl> <date> <date>
1 1 1992-02-26 1992-02-27
2 2 1992-01-14 1992-02-01
3 3 1992-02-28 <NA>https://stackoverflow.com/questions/39691369
复制相似问题