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

Apply a function to dataframe - arguments must have the same length

我得到了一个包含两个参数的巨大数据集 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

您可以使用软件包 dplyr,例如:

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

你可以用任何你喜欢的函数来代替 mean()

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

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.