2017-02-04 143 views
1

有人能告訴我爲什麼我在用日期重塑時遇到困難。我想從這裏去:用日期重塑長到寬 - R

#Data frame 
date = c("01/03/15", "03/04/12", "07/21/16","09/08/16") 
id = c(1,1,2,2) 
df = data.frame(id,date) 

#Convert to date 
df$date <- as.Date(df$date, "%m/%d/%y") 

#Reshape 
library(reshape) 
a <- reshape(df, idvar = "id", timevar = "date", direction = "wide") 

到這裏:

#Final date frame 
date.2 = c("03/04/12", "09/08/16") 
date.1 = c("01/03/15", "07/21/16") 
id = c(1,2) 
df = data.frame(id,date.1,date.2) 

感謝您的幫助。

回答

1

我們可以使用dcast

library(data.table) 
dcast(setDT(df), id~paste0("date.", rowid(id)), value.var = "date") 
# id  date.1  date.2 
#1: 1 2015-01-03 2012-03-04 
#2: 2 2016-07-21 2016-09-08 

或者使用tidyverse

library(dplyr) 
library(tidyr) 
df %>% 
    group_by(id) %>% 
    mutate(i1 = paste0("date.", row_number())) %>% 
    spread(i1, date) 
+0

感謝@akrun。好奇,重塑不適合日期? – richiepop2

+0

@ nchiepop2你的意思是'reshape'函數,對吧。爲此你需要有一個序列列 – akrun