2016-03-06 79 views
0

我(樣品)的數據結構如下:如何通過分組變量來計算一列相對於另一列的百分比?

Individ <- data.frame(Participant = c("Bill", "Bill", "Bill", "Bill", "Bill", "Bill", "Bill", "Bill", "John", "John", "John", "John", 
             "Harry", "Harry", "Harry", "Harry","Harry", "Harry", "Harry", "Harry", "Paul", "Paul", "Paul", "Paul"), 
         Time = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4), 
         Condition = c("Placebo", "Placebo", "Placebo", "Placebo", "Expr", "Expr", "Expr", "Expr", "Expr", "Expr", "Expr", "Expr", 
            "Placebo", "Placebo", "Placebo", "Placebo", "Expr", "Expr", "Expr", "Expr", "Expr", "Expr", "Expr", "Expr"), 
         Power = c(400, 250, 180, 500, 300, 450, 600, 512, 300, 500, 450, 200, 402, 210, 130, 520, 310, 451, 608, 582, 390, 570, 300, 200)) 

我使用計算下的每個Condition的平均工作由每個Participant完成以下任務:

IndividAvgWork <- ddply(Individ, c("Participant", "Condition"), summarise, 
         Power = mean(Power)) 

我現在要計算Power執行在data.frame Individ中的每分鐘Time,作爲IndividAvgWork中的總平均功率的百分比。這必須在每個Condition下的每個Participant完成。有沒有一個快速的方法來做到這一點?

我的預期輸出的一個例子,爲比爾安慰劑狀況期間,將是:(採樣功率/平均功率)* 100:

RelPower = c(120.30, 75.19, 54.14, 150.38) 

上面被計算。

作爲工作例子,比爾的Power在1安慰劑Condition下一個Time是400我再由平均功率安慰劑Condition是332.50和存儲在IndividAvgWork下分此爲比爾。將這些值代入給出:(400/332.5)* 100

謝謝。

回答

0

你可以嘗試這樣的事情利用圖書館dplyr

library(dplyr) 
Individ %>% group_by(Participant, Condition) %>% mutate(PercentPower = round(Power/(mean(Power)) * 100, 2)) 

這是它會產生:

Source: local data frame [24 x 5] 
Groups: Participant, Condition [6] 

    Participant Time Condition Power PercentPower 
     (fctr) (dbl) (fctr) (dbl)  (dbl) 
1   Bill  1 Placebo 400  120.30 
2   Bill  2 Placebo 250  75.19 
3   Bill  3 Placebo 180  54.14 
4   Bill  4 Placebo 500  150.38 
5   Bill  1  Expr 300  64.45 
6   Bill  2  Expr 450  96.67 
7   Bill  3  Expr 600  128.89 
8   Bill  4  Expr 512  109.99 
9   John  1  Expr 300  82.76 
10  John  2  Expr 500  137.93 
..   ... ...  ... ...   ... 
+0

謝謝。你知道我爲什麼在我的問題旁邊有-1嗎? – user2716568

+0

它被拒絕了,因爲你原來的問題不清楚。在編輯之後,它再次被投票否定'-1'。 – Gopala