将函数应用于数据框 - 参数必须具有相同的长度

时间:2018-04-19 12:17:27

标签: r function tapply

我收到了两个参数的大量数据集xqssc。它们按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)
}

最后得到两个值hefoo1的矩阵。我试图使用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

2 个答案:

答案 0 :(得分:0)

您可以使用包dplyr,例如:

result <- x %>% group_by(he) %>% summarise(q_avg = mean(q), ssc_avg = mean(ssc))

您可以使用您喜欢的任何功能而不是mean()

答案 1 :(得分:0)

我对你的功能进行了2次更改。首先,您传递i但在函数中使用x - 因此我在您的函数中将x更改为i。其次,我没有返回numeric,而是将结果添加到grouped.data.frame的末尾并返回

foo1 <- function(i) {
    M <- lm(log(ssc) ~ I(log(q)), data = i)
    a <- exp(coef(M)[1])
    b <- coef(M)[2]
    res <- i$ssc - a*i$q^b
    r <- mean(res[1:which.max(i$q)])
    f <- mean(res[c((which.max(i$q)+1):length(i$q))])
    i$HI <- r-f
    return(i)
}

使用group_by(...) %>% do(function(...))按群组应用功能

x %>%
  group_by(he) %>%
  do(foo1(.)) %>%
  ungroup()

# A tibble: 14 x 4
# Groups: he [2]
       # q   ssc    he     HI
   # <dbl> <dbl> <dbl>  <dbl>
 # 1  1.62  238.    1.   207.
 # 2  1.82  388.    1.   207.
 # 3  2.09  721.    1.   207.
 # 4  2.48  744.    1.   207.
 # 5  2.19  307.    1.   207.
 # 6  1.87  246.    1.   207.
 # 7  1.67  222.    1.   207.
 # 8  1.44  216.    2. -1961.
 # 9  1.80  228.    2. -1961.
# 10  2.52 1169.    2. -1961.
# 11  2.27 5150.    2. -1961.
# 12  1.83 2217.    2. -1961.
# 13  1.68  641.    2. -1961.
# 14  1.54  304.    2. -1961.
相关问题