SummaryBy 函数

Function for SummaryBy

我尝试编写一个函数来生成 mean 和 sd

library(doBy)
fun = function(x){
  mean = mean(x, na.rm = TRUE)
  sd = sd(x, na.rm = TRUE)
  c(mean, sd)
  }

summaryBy(mpg~am, data = mtcars, FUN=fun)

它可以调用 summaryBy,但是当我尝试放入函数来调用变量和数据集的名称时,它给我错误

"Error in list(mpg, am, mtcars) : (list) object cannot be coerced to type 'double"

list <- function(x,y,dataset){
  x <- as.numeric(x)
  y <- as.factor(y)
  table <- summaryBy(x~y, data = dataset, FUN=fun)
  table

}

list(mpg, am, mtcars)

感谢您的建议

这与 summaryBy 无关,这是您的 list 函数代码中的一个错误。 (顺便说一句,你不应该命名一个函数 "list",因为这已经是 R 中一个重要函数的名称,你最终会遇到问题。)试试这个(你需要输入变量名在引号中):

my.tab <- function(x, y, dataset){
  xn <- with(dataset, as.numeric(get(x)))
  yf <- with(dataset, as.factor(get(y)))
  newdf <- data.frame(xn=xn, yf=yf)
  names(newdf) <- c(x, y)
  table <- summaryBy(as.formula(paste0(x,"~",y)), data=newdf, FUN=fun)
  table
}
my.tab("mpg", "am", mtcars)
#   am mpg.FUN1 mpg.FUN2
# 1  0 17.14737 3.833966
# 2  1 24.39231 6.166504

问题是当您调用函数 list 时,mpgam 不是全局环境中的变量。做你想做的,更改函数签名以输入公式并使用公式调用函数:

list <- function(f, dataset){
  return(summaryBy(f, data = dataset, FUN=fun))
}
table <- list(as.formula(mpg~am), mtcars)
print(table)
##  am mpg.FUN1 mpg.FUN2
##1  0 17.14737 3.833966
##2  1 24.39231 6.166504

希望对您有所帮助。