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

我要做的是合并每个配置文件内的深度重复,计算合并重复的 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 列的平均值以获取合并深度。有什么提示吗?提前非常感谢。

4

2 回答 2

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
于 2013-03-18T22:14:32.697 回答
2

X您必须以与添加相同的方式为unY值添加计算和名称Depth

 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
于 2013-03-18T15:49:17.627 回答