【问题标题】:Apply a function to dataframe - arguments must have the same length将函数应用于数据框 - 参数必须具有相同的长度
【发布时间】:2018-04-19 12:17:26
【问题描述】:

我有一个巨大的数据集x,有两个参数:qssc。它们按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

【问题讨论】:

  • 你说...&lt;- function(i){..... data = x...}x 是什么,i 在哪里?
  • 使用lapply(split(x, x$he), foo1) 在数据集中的每个组上使用该函数。输出将是一个列表。而且,正如@Sotos 所提到的,当您使用x 作为函数中的数据变量时,请确保foo1 &lt;- function(x)

标签: r function tapply


【解决方案1】:

我对您的函数进行了 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(...) %&gt;% 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.

【讨论】:

  • 感谢您的功能升级和非常简单的解决方案
【解决方案2】:

你可以用包dplyr,比如:

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

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

【讨论】:

    猜你喜欢
    • 2019-12-19
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 2017-06-22
    • 1970-01-01
    相关资源
    最近更新 更多