我必须通过因子找出连续变量的累积频率(换算成百分比)。 例如:
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
因子列Plot~Site
列的累积频率,以便为每个地块和网站绘制G
的{{1}}与d
的geom_step ggplot。
我已经实现了按因子计算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
现在,我需要在[0..1]范围内表达每个Plot
G
,其中1 G
为每个Plot
。我想我应该将G
除以Plot
Gtot
,然后对其应用新的cumsum
。怎么做?
请注意,我必须将此累积频率与d
而不是G
本身进行绘制,因此它不是一个合适的ecdf。
谢谢。
答案 0 :(得分:8)
我通常使用ddply
和transform
来执行此类操作:
> 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)