2017-04-27 59 views
5

我想爲多列中的多個值提取一些摘要統計信息。我的數據看起來如下如何獲取每個唯一ID的摘要

id    pace  type     value  abundance 
51    (T)  (JC)     (L)   0   
51    (T)  (JC)     (L)   0 
51    (T)  (JC)     (H)   0 
52    (T)  (JC)     (H)   0 
52    (R)  (JC)     (H)   0 
53    (T)  (JC)     (L)   1 
53    (T)  (JC)     (H)   1 
53    (R)  (JC)     (H)   1 
53    (R)  (JC)     (H)   1 
53    (R)  (JC)     (H)   1 
54    (T)  (BC)     <blank>   0   

54    (T)  (BC)     <blank>   0 
54    (T)  (BC)     <blank>   0 

,我希望這樣的事情

id ptype  (T) (R)  (L)  (H)  abundance 
51  (JC)  3  0   2  1   0 
52  (JC)  1  1   0  2   0 
53  (JC)  2  3   1  4   1 
54  (BC)  3  0   0  0   0 

我已經開始寫一些代碼:

for (i in levels(df$id)) 
{ 
    extract.event <- df[df$id==i,]# To identify each section 
ppace <- table(extract.event$pace) #count table of pace 
ptype <- extract.event$type[1] # extract the first line to be the type 
nvalues <- table(extract.event$value) #count table of value 
nabundance <- min(extract.event$abundance) #minimum of abundance 

d <- cbind(ppace,ptype,forbeh,nvalues,nabundance) 

,但我遇到了合併值問題,尤其是當nabundance打印出一張空白表格時。我不想按名稱提取,因爲數據框中有很多名字。有任何想法嗎?我想這可能是是與plyr包,但仍不能確定......

感謝,

格雷斯

回答

3

我不得不重寫你的data.frame(以供將來參考,請貼上結果因爲我們討厭重寫你的數據),但這是我的嘗試。我猜你正在尋找沿聚合函數線的東西:

df <- data.frame(id = as.factor(c(51,51,51,52,52,53,53,53,53,53,54,54,54)), 
     pace = c("(T)","(T)","(T)","(T)","(R)","(T)","(T)","(R)","(R)","(R)","(T)","(T)","(T)"), 
     type = c("(JC)","(JC)","(JC)","(JC)","(JC)","(JC)","(JC)","(JC)","(JC)","(JC)","(BC)","(BC)","(BC)"), value = c("(L)","(L)","(H)","(H)","(H)","(L)","(H)","(H)","(H)","(H)","<blank>","<blank>","<blank>"), 
     abundance = c(0,0,0,0,0,1,1,1,1,1,0,0,0)) 

smallnames <- colnames(do.call("cbind",as.list(aggregate(cbind(value, pace, abundance) ~ id + type, data = lapply(df, as.character), table)))) 
smallnames 
[1] "id"  "type" "(H)"  "(L)"  "<blank>" "(R)"  "(T)"  "0"  
[9] "1" 

df.new <- do.call("data.frame", as.list(aggregate(cbind(value, pace, abundance) ~ id + type, data = lapply(df, as.character), table))) 
colnames(df.new) <- smallnames 
df.new$abundance <- df.new$`1` 
df.new 
    id type (H) (L) <blank> (R) (T) 0 1 abundance 
1 54 (BC) 0 0  3 0 3 3 0   0 
2 51 (JC) 1 2  0 0 3 3 0   0 
3 52 (JC) 2 0  0 1 1 2 0   0 
4 53 (JC) 4 1  0 3 2 0 5   5 

df.final <- df.new[, -which(colnames(df.new) %in% c("<blank>","0","1"))] 
df.final 
    id type (H) (L) (R) (T) abundance 
1 54 (BC) 0 0 0 3   0 
2 51 (JC) 1 2 0 3   0 
3 52 (JC) 2 0 1 1   0 
4 53 (JC) 4 1 3 2   5 

讓我知道這是你正在尋找,或者如果你有麻煩了什麼。

+0

查看編輯其中第2部分與您所需的數據幀輸出類似 –

+2

'聚合(cbind(value,pace,abundance)〜id + type,data = lapply(df,as.character),table)似乎幾乎得到有一點容易 – user2957945

+0

這是一個整齊的代碼行,但你會注意到一旦你增加丰度,你處理0和1的計數。另外,聚合實際上留下了一個矩陣的數據框在裏面。 Part1在as.list聚合對象上使用do.call + cbind來使名稱更清晰(如問)和正確格式化(簡單的data.frame)。第二部分(雖然看起來醜陋)只是迫使事情看起來像OP問。我確實喜歡使用cbind,+1 –