2016-04-13 83 views
0

大家好我有一個表[R變換多個行轉換成列

id sample_name replicates raw 
a control  c1   1 
a control  c2   2 
a control  c3   3 
b control  c1   10  
b control  c2   20 
b control  c3   20 

,並想這個我知道如何做到這一點的唯一方法轉化爲

id c1 c2 c3 
a 1 2 3  
b 10 20 20 

是通過暴力循環每3個,因爲有3個複製,並將其附加到多個向量,並在末尾重新組合到一個數據幀,因此我想知道是否有一個更優雅/簡單的方法來做到這一點?謝謝!

+1

你的數據是「長」的形式 - 你希望它在「寬」的形式。在R標籤中搜索「long to wide」,你會發現很多例子,特別是使用'reshape2 :: dcast'或'tidyr :: spread'。 – Gregor

+1

'reshape2 :: dcast(df,id〜replicates,value.var ='raw')' – alistaire

+0

@alistaire謝謝!正是我需要的。對不起,冗餘。 – Ahdee

回答

1

嘗試......

> library(reshape2) 
> dcast(melt(df[, -2]), ...~replicates)[, -2] 
Using id, replicates as id variables 
    id c1 c2 c3 
1 a 1 2 3 
2 b 10 20 20