[英]Reshape long to wide with dates - R
Can someone tell me why I'm having trouble reshaping with dates.有人能告诉我为什么我在用日期重塑时遇到问题吗? I'd like to go from here:我想从这里去:
#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")
to here:到这里:
#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)
Thanks for your help.谢谢你的帮助。
We can use dcast
我们可以使用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
Or using tidyverse
或者使用tidyverse
library(dplyr)
library(tidyr)
df %>%
group_by(id) %>%
mutate(i1 = paste0("date.", row_number())) %>%
spread(i1, date)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.