使用基本 R 选项reshape
reshape(
transform(
df,
q = ave(1:nrow(df), ID, FUN = seq_along)
),
direction = "wide",
idvar = "ID",
timevar = "q"
)
给
ID Product.1 Date.1 Product.2 Date.2 Product.3 Date.3
1 1 Bike 1/1/2000 Tire 2/1/2000 Chronometer 20/2/2000
3 2 Car 15/2/2000 Seat 17/2/2000 <NA> <NA>
如果你不想保留Date
,你可以试试这个
reshape(
transform(
subset(df, select = -Date),
q = ave(1:nrow(df), ID, FUN = seq_along)
),
direction = "wide",
idvar = "ID",
timevar = "q"
)
这使
ID Product.1 Product.2 Product.3
1 1 Bike Tire Chronometer
3 2 Car Seat <NA>
数据
> dput(df)
structure(list(ID = c(1L, 1L, 2L, 2L, 1L), Product = c("Bike",
"Tire", "Car", "Seat", "Chronometer"), Date = c("1/1/2000", "2/1/2000",
"15/2/2000", "17/2/2000", "20/2/2000")), class = "data.frame", row.names = c(NA,
-5L))