簡體   English   中英

重塑R,行向量

[英]Reshape in R, rows to vectors

我的數據如下所示:

fruit          ID
apple          1
mango          1
orange         1
grapes         2
strawberries   3

我想使用重塑來做的是:

ID     Fruit
 1     apple,mango,orange 
 2     grapes
 3     strawberries

我嘗試重塑

rehshape(data=test,direction="long",varying=c(1,2),v.names="v1",timevar="v2",times=c(1,2))->test.long              

但這顯然是錯誤的。

您可以嘗試aggregate

aggregate(fruit ~ ID, data , paste, sep=',')

  ID                fruit
1  1 apple, mango, orange
2  2               grapes
3  3         strawberries

由於其他所有人都有aggregate ,因此這是一種讓您reshape的方法:在您的data.frame添加一個時間變量,然后嘗試從長到寬進行重塑。 假設原始的data.frame稱為“ mydf”:

> # Create a time variable
> mydf$time <- ave(mydf$ID, mydf$ID, FUN = seq_along)
> mydf
         fruit ID time
1        apple  1    1
2        mango  1    2
3       orange  1    3
4       grapes  2    1
5 strawberries  3    1

> # Now, reshape
> reshape(mydf, direction = "wide", idvar = "ID", timevar = "time")
  ID      fruit.1 fruit.2 fruit.3
1  1        apple   mango  orange
4  2       grapes    <NA>    <NA>
5  3 strawberries    <NA>    <NA>

嘗試這個

> aggregate(fruit~ID, data=DF, FUN=paste0)
  ID                fruit
1  1 apple, mango, orange
2  2               grapes
3  3         strawberries

暫無
暫無

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

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