如何解决使用多个时间变量重塑数据表
我有一个数据集 DT
,其中每一行代表一个人在比赛中的表现:
personID | 比赛日期 | 种族ID | finPos |
---|---|---|---|
person1 | 2009-08-14 | 489801 | 2 |
person1 | 2010-04-17 | 502397 | 6 |
person1 | 2011-03-10 | 524554 | 4 |
person2 | 2009-08-14 | 489801 | 1 |
person2 | 2011-03-10 | 524554 | 3 |
... | ... | ... | ... |
我想转换数据集,使每人有 1 行,并按比赛日期的顺序列出他们的比赛表现(未参加特定比赛的个人的 NA 值)。例如:
personID | 489801 | finPos | 502397 | finPos | 524554 | finPos |
---|---|---|---|---|---|---|
person1 | 2009-08-14 | 2 | 2010-04-17 | 6 | 2011-03-10 | 4 |
person2 | 2009-08-14 | 1 | 不适用 | 不适用 | 2011-03-10 | 3 |
例如,我知道我可以通过 reshape2 获得部分效果:
reshape(DT,direction = "wide",idvar = "raceID",timevar = "raceDate")
但是有没有办法确保raceID/raceDat/finishPos的组合保持在一起?
解决方法
data.table
方法
library(data.table)
DT <- fread("personID raceDate raceID finPos
person1 2009-08-14 489801 2
person1 2010-04-17 502397 6
person1 2011-03-10 524554 4
person2 2009-08-14 489801 1
person2 2011-03-10 524554 3")
# Cast to wide
cols <- c("raceDate","finPos") #value columns to cast
answer <- dcast(DT,personID ~ raceID,value.var = cols,drop = FALSE)
现在数据被转换为宽,但按值变量“分组”。您现在需要做的就是对列重新排序...
# Determine column order
new_col_order <- CJ( sort(unique(DT$raceID)),cols,sorted = FALSE)[,paste(cols,V1,sep = "_")]
# Set new column order
setcolorder(answer,c(setdiff(names(answer),new_col_order),new_col_order))
# personID raceDate_489801 finPos_489801 raceDate_502397 finPos_502397 raceDate_524554 finPos_524554
# 1: person1 2009-08-14 2 2010-04-17 6 2011-03-10 4
# 2: person2 2009-08-14 1 <NA> NA 2011-03-10 3
,
这是一个整洁的方法。数据对在一起,但我按顺序交换了它们。
library(tidyr)
DT %>%
pivot_wider(id_cols = personID,names_from = c(raceID),names_glue = "{raceID}_{.value}",values_from = c(raceDate,finPos)) %>%
select(personID,sort(colnames(.)))
## A tibble: 2 x 7
# personID `489801_finPos` `489801_raceDate` `502397_finPos` `502397_raceDate` `524554_finPos` `524554_raceDate`
# <chr> <int> <chr> <int> <chr> <int> <chr>
#1 person1 2 2009-08-14 6 2010-04-17 4 2011-03-10
#2 person2 1 2009-08-14 NA NA 3 2011-03-10
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。