Non-standard evaluation of subset argument with mapply in R

吃可爱长大的小学妹 提交于 2020-01-05 09:47:29

问题


I can not use the subset argument of any function with mapply. The following calls fail with the subset argument, but they work without:

mapply(ftable,
       formula = list(wool ~ breaks,
                      wool + tension ~ breaks),
       subset = list(breaks < 15,
                     breaks < 20),
       MoreArgs = list(data = warpbreaks))

# Error in mapply(ftable, formula = list(wool ~ breaks, wool + tension ~  : 
#   object 'breaks' not found

mapply(xtabs,
       formula = list(~ wool,
                      ~ wool + tension),
       subset = list(breaks < 15,
                     breaks < 20),
       MoreArgs = list(data = warpbreaks))

# Error in mapply(xtabs, formula = list(~wool, ~wool + tension), subset = list(breaks <  : 
#   object 'breaks' not found

Map(lm,
    formula = list(breaks ~ wool,
                   breaks ~ tension),
    subset = list(breaks < 15,
                  breaks < 20),
    MoreArgs = list(data = warpbreaks))

# Error in mapply(FUN = f, ..., SIMPLIFY = FALSE) : 
#   object 'breaks' not found

The error seems to be due to subset arguments not being evaluated in the right environment. I know I can subset in the data argument with data = warpbreaks[warpbreaks$breaks < 20, ] as a workaround, but I am looking to improve my knowledge of R.

My questions are:

  • Why is the formula argument evaluated in data = warpbreaks, but the subset argument is not?
  • I wrote a wrapper around ftable because I need to compute flat tables with frequency and percentage for many variables (more details in my previous questions). Can I modify the wrapper to use the subset argument of ftable in mapply?

.

# the wrapper
mytable <- function(...) {
    mc <- match.call()
    mc[[1]] <- quote(expr = ftable)
    eval.parent(expr = mc)
    # etc
}

来源:https://stackoverflow.com/questions/56817969/non-standard-evaluation-of-subset-argument-with-mapply-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!