2012-01-16 137 views
6

我必須找出連續變量按因子計算的累計頻率,轉換爲百分比。 例如:按因子計算的累計頻率

data <- data.frame(n = sample(1:12), 
       d = seq(10, 120, by = 10), 
       Site = rep(c("FirstSite", "SecondSite"), 6), 
       Plot = rep(c("Plot1", "Plot1", "Plot2", "Plot2"), 3) 
       ) 

data <- with(data, data[order(Site,Plot),]) 
data <- transform(data, G = ((pi * (d/2)^2) * n)/10000) 

data 
    n d  Site Plot   G 
1 7 10 FirstSite Plot1 0.05497787 
5 9 50 FirstSite Plot1 1.76714587 
9 12 90 FirstSite Plot1 7.63407015 
3 10 30 FirstSite Plot2 0.70685835 
7 5 70 FirstSite Plot2 1.92422550 
11 1 110 FirstSite Plot2 0.95033178 
2 3 20 SecondSite Plot1 0.09424778 
6 8 60 SecondSite Plot1 2.26194671 
10 6 100 SecondSite Plot1 4.71238898 
4 4 40 SecondSite Plot2 0.50265482 
8 2 80 SecondSite Plot2 1.00530965 
12 11 120 SecondSite Plot2 12.44070691 

我需要因素G列的cumulaive頻率Plot~Site爲了繪製的G一個geom_step ggplot針對d每個情節和站點。
我已經實現通過因子通過以計算G累計總和:

data.ss <- by(data[, "G"], data[,c("Plot", "Site")], function(x) cumsum(x)) 
# Gtot 
(data.ss.tot <- sapply(ss, max)) 
[1] 9.456194 3.581416 7.068583 13.948671 

現在我需要表達在其中1是G TOT爲每個Plot範圍[0..1]的每個PlotG。我想我應該劃分GPlotGtot,然後應用一個新的cumsum它。怎麼做?
請注意,我必須將此累積頻率與d而不是G本身進行比較,所以它不是一個合適的ecdf。
謝謝。

回答

8

我通常使用ddplytransform做這種類型的事情:

> data = ddply(data, c('Site', 'Plot'), transform, Gsum=cumsum(G), Gtot=sum(G)) 
> qplot(x=d, y=Gsum/Gtot, facets=Plot~Site, geom='step', data=data) 

enter image description here

+0

非常優雅的解決方案,謝謝。 – mbask 2012-01-17 04:28:44