如何计算函数

时间:2017-01-25 22:37:41

标签: r statistics

我想计算函数内部列的平均值。我们试试这个例子:

test = data.frame(value = c(231,43,12,342,123,543,56,122,321,222),
              category = c("A","B","A","B","A","A","A","B","B","B"))


  fun <- function(AorB) {
  example <- test %>% 
   filter(category == AorB) %>%
   select(value) 
   ## %>%           (here I want to add mean calculation)
   ## mean()        (it is not possible)
   ## sum()/nrow    (it is not possible)
  }

  solve <- fun("A")

'mean()'和'sum()/ nrow()'的整个问题是'mean()'和'nrow()'需要指定data.frame。所有计算都在函数内部,所以我不能像这样指定data.frame:

mean(example$value)

1 个答案:

答案 0 :(得分:0)

Per Sin在评论中提出的建议......

我认为您需要使用:

example <- test %>% filter(category == AorB) %>% summarise( mean = mean(value))

对于dplyr,您需要在summarize()函数中调用(并命名)这些汇总函数。