这是我的数据集:
C1 C2 C3 C4 C5 C6 C7 C8
ATOM 1 -4.794 -7.29 6.756 C 12 1
ATOM 1 -4.357 -6.181 6.473 O 16 1
ATOM 2 -5.279 -7.475 5.986 C 12 1
ATOM 2 -7.564 -8.809 6.984 C 12 1
ATOM 2 -5.822 -7.105 7.238 C 12 1
ATOM 1 -7.515 -10.402 -0.621 C 12 2
ATOM 1 -7.26 -11.716 -0.22 O 16 2
ATOM 1 -8.163 -9.682 0.566 C 12 2
ATOM 2 -6.347 -9.475 -1.255 C 12 2
ATOM 1 -7.302 -8.048 7.702 C 12 3
ATOM 1 -7.676 -8.93 6.667 C 12 3
ATOM 2 -6.864 -9.118 5.529 C 12 3
我的目标是根据C8列的内容对数据进行子集化,并使用循环运行一系列计算。我目前正在通过运行:
手动完成sub.1 <- subset(data, C8 == 1)
result.1 <- within(data, {
multiply.z <- C5 * C7
multiply.y <- C4 * C7
multiply.x <- C3 * C7
Center.z <- sum(multiply.z)/sum(C7)
Center.y <- sum(multiply.z)/sum(C7)
Center.x <- sum(multiply.z)/sum(C7)
#rm(multiply.z,multiply.y,multiply.x)
})
sub.2 <- subset(data, C8 == 2)
result.2 <- same code as above
sub.3 <- subset(data, C8 == 3)
result.3 <- same code as above
我尝试使用for循环自动执行上述操作,但它无法正常工作。这是我的代码:
for ( i in 1:max(C8)){
sub.i <- subset(data, C8 == i)
result.i <- within(sub.i, {
multiply.z <- C5 * C7
multiply.y <- C4 * C7
multiply.x <- C3 * C7
Center.z <- sum(multiply.z)/sum(C7)
Center.y <- sum(multiply.z)/sum(C7)
Center.x <- sum(multiply.z)/sum(C7)
#rm(multiply.z,multiply.y,multiply.x)
})}
如果您有任何关于如何解决此问题的帮助或建议,我将不胜感激。提前谢谢!
答案 0 :(得分:1)
您当然希望仔细查看包含此类任务所需的所有工具的library(plyr)
。它允许您使用函数ddply
,
library(plyr)
mySubs <- ddply(dat, .(C8), .fun = function(x) {
multiply.z = x$C5 * x$C7
multiply.y = x$C4 * x$C7
multiply.x = x$C3 * x$C7
Center.z = sum(multiply.z)/sum(x$C7)
Center.y = sum(multiply.z)/sum(x$C7)
Center.x = sum(multiply.z)/sum(x$C7)
##rm(multiply.z,multiply.y,multiply.x)
data.frame(z = Center.z, y = Center.y, x = Center.x)
})
在这里返回data.frame(ddply是一个子集data.frames并返回data.frames的函数,由其名称中的'dd'隐含,plyr函数使用的约定)。
> mySubs
C8 z y x
1 1 6.674000 6.674000 6.674000
2 2 -0.370000 -0.370000 -0.370000
3 3 6.632667 6.632667 6.632667
等...
答案 1 :(得分:1)
这是一个data.table
解决方案:
library(data.table)
DT <- data.table(df)
DT[,
structure(
lapply(list(C5, C4, C3), function(x) sum(x * C7) / sum(C7) ),
names = c("z", "y", "x")
)
, by = C8]
## C8 z y x
## 1: 1 6.674000 -7.297562 -5.487813
## 2: 2 -0.370000 -10.426231 -7.316538
## 3: 3 6.632667 -8.698667 -7.280667