2014-01-28 73 views
0

原始表:轉換多行單列中的R

ID------REMARK 

1------ A 

2------ B 

1-------AG 

3-------V 

2-------BS 

1--------E 

4--------B 

4--------BS 

所需的表:

ID......REMARK 

1-------A,AG,E 

2-------B,BS 

3-------V 

4-------B,BS 

然後根據頻繁發生的序列列表:

REMARK......OCCURRENCES 


A,AG,E-------1 

B,BS---------2 

V -----------1 
+2

歡迎計算器。請閱讀[**關於Stackoverflow **](http://stackoverflow.com/about)和[**要問什麼**](http://stackoverflow.com/help/on-topic)。正如你將在這兩個鏈接中發現的,你應該「展示你的工作」,並且「詢問代碼的問題必須顯示對所解決問題的最小理解,包括嘗試的解決方案,爲什麼他們不工作以及預期的結果」 。謝謝。 – Henrik

+2

請不要將CAPITALS用於普通文本... – SlowLearner

回答

3

這是一種方法。 dat是你的數據幀的名稱:

res1 <- aggregate(REMARK ~ ID, dat, paste, collapse = ",") 
# ID REMARK 
# 1 1 A,AG,E 
# 2 2 B,BS 
# 3 3  V 
# 4 4 B,BS 

table(res1$REMARK) 
# 
# A,AG,E B,BS  V 
#  1  2  1 
1

這裏是一個plyr解決方案:

library(plyr) 
dt.agg <- ddply(dt, .(ID), summarise, Remark = paste(REMARK, collapse = ",", sep = "") ) 
ddply(dt.agg, .(Remark), nrow) 

    Remark V1 
1 A,AG,E 1 
2 B,BS 2 
3  V 1