【发布时间】:2018-04-19 12:17:26
【问题描述】:
我有一个巨大的数据集x,有两个参数:q 和ssc。它们按he 值分组。
每个he 都是一个循环。有大量的组(≈100)。
x <- data.frame(q = c(1.62, 1.82,2.09, 2.48, 2.19, 1.87, 1.67,1.44,1.8,2.52,2.27,1.83,1.68,1.54),
ssc = c(238, 388, 721, 744, 307, 246, 222,216,228,1169,5150,2217,641,304),
he = c(1,1,1,1,1,1,1,2,2,2,2,2,2,2))
plot(ssc~q, type = "o", group = he, data = x)
我想申请我在foo1等功能上的每个组:
foo1 <- function(i) {
M <- lm(log(ssc) ~ I(log(q)), data = x)
a <- exp(coef(M)[1])
b <- coef(M)[2]
res <- x$ssc - a*x$q^b
r <- mean(res[1:which.max(x$q)])
f <- mean(res[c((which.max(x$q)+1):length(x$q))])
HI <- r-f
return(HI)
}
最后得到两个值的矩阵he,foo1。我试图使用tapply,但无法弄清楚如何让它使用 2 个输入行(q 和 ssc):
tapply(X = list(x$q, x$ssc), x$he, foo1)
>Error in tapply(X = list(x$q, x$ssc), x$he, foo1) :
>arguments must have the same length
【问题讨论】:
-
你说
...<- function(i){..... data = x...}。x是什么,i在哪里? -
使用
lapply(split(x, x$he), foo1)在数据集中的每个组上使用该函数。输出将是一个列表。而且,正如@Sotos 所提到的,当您使用x作为函数中的数据变量时,请确保foo1 <- function(x)。