簡體   English   中英

如何使用重塑包重塑r中的數據

[英]how to reshape data in r with reshape package

我有如下數據:

Id    date         result
1     12/2/1997    1
1     04/5/2000    0
2     06/4/1998    1
2     18/6/1999    1
2     20/3/2000    0

我希望它看起來像:

Id date.1    result.1 date.2     result.2 date.3    result.3
1  12/2/1997 1        04/5/2000  0        na        na
2  06/4/1998 1        18/6/1999  1        20/3/2000 0

你可以試試

df$indx <- with(df, ave(seq_along(Id), Id, FUN=seq_along))
df1 <- reshape(df, idvar='Id', timevar='indx', direction='wide')
df1
#   Id    date.1 result.1    date.2 result.2    date.3 result.3
#1  1 12/2/1997        1 04/5/2000        0      <NA>       NA
#3  2 06/4/1998        1 18/6/1999        1 20/3/2000        0

更新資料

如果要使用indx添加新列

 df1$newCol <- tail(unique(df$indx), nrow(df1))
 df1
 #  Id    date.1 result.1    date.2 result.2    date.3 result.3 newCol
 #1  1 12/2/1997        1 04/5/2000        0      <NA>       NA      2
 #3  2 06/4/1998        1 18/6/1999        1 20/3/2000        0      3

數據

df <- structure(list(Id = c(1L, 1L, 2L, 2L, 2L), date = c("12/2/1997", 
"04/5/2000", "06/4/1998", "18/6/1999", "20/3/2000"), result = c(1L, 
0L, 1L, 1L, 0L)), .Names = c("Id", "date", "result"), class = "data.frame",
row.names = c(NA, -5L))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM