2013-03-18 70 views
3

我有一個X,Y配置文件編號和相關聯的深度地理座標定位的數據集:合併重複的各種因素,並計算平均

Dataset 
X = c(1:10) 
Y=c(11:20) 
Profile=c(298,298,298,299,299,299,300,300,301,301) 
Depth=c(-1,-1,-2,-1,-2,-3,-1,-1,-1,-2) 
df=as.data.frame(cbind(X,Y,Profile,Depth)) 

我的數據集是這樣的:

 X Y Profile Depth 
1 1 11  298 -1 
2 2 12  298 -1 
3 3 13  298 -2 
4 4 14  299 -1 
5 5 15  299 -2 
6 6 16  299 -3 
7 7 17  300 -1 
8 8 18  300 -1 
9 9 19  301 -1 
10 10 20  301 -2 

我試圖做的是合併每個配置文件中的Depth重複項,計算合併重複項的X和Y的平均值並保持配置文件編號關聯。

我可以通過配置文件使用包plyr合併重複:

out=ddply(df,.(Profile,Depth),summarize, Depth=unique(Depth)) 

    Profile Depth 
1  298 -2 
2  298 -1 
3  299 -3 
4  299 -2 
5  299 -1 
6  300 -1 
7  301 -2 
8  301 -1 

但我不能找到一種方法來提取我的X和Y列的均值爲合併的深度。 任何提示?提前致謝。

+0

+1對於蘇明確寫出第一個問題,並列入一個可重複的例子!歡迎來到SO。 – 2013-03-18 16:30:08

回答

2

您必須使用與Depth相同的方式爲X un Y添加計算和名稱。

ddply(df,.(Profile,Depth),summarize, X=mean(X),Y=mean(Y), Depth=unique(Depth)) 
    Profile X Y Depth 
1  298 3.0 13.0 -2 
2  298 1.5 11.5 -1 
3  299 6.0 16.0 -3 
4  299 5.0 15.0 -2 
5  299 4.0 14.0 -1 
6  300 7.5 17.5 -1 
7  301 10.0 20.0 -2 
8  301 9.0 19.0 -1 
+0

謝謝我欣賞,我試圖把計算作爲函數(x).... – 2013-03-18 16:11:09

2

data.table替代。這將比ddply更快,並且它將針對大數據進行擴展。 它也少打字!

library(data.table) 
    DT <- data.table(df) 
    DT[, lapply(.SD, mean) ,by = list(Profile, Depth)] 

  • .SD是data.table每個組
  • lapply(.SD, mean)的子集將計算平均值爲每列在.SD
  • 如果你只是想的一個子集列,你會通過這.SDcols