有人可以告诉我为什么我在重新设定日期方面遇到了麻烦。我想离开这里:
#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)
感谢您的帮助。
答案 0 :(得分: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)