在函数内的lapply中调用update,为什么它不起作用? [英] Calling update within a lapply within a function, why isn't it working?

查看:103
本文介绍了在函数内的lapply中调用update,为什么它不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题来自的后续问题

This a a follow up question from Error in calling `lm` in a `lapply` with `weights` argument but it may not be the same problem (but still related).

以下是可重现的示例:

dd <- data.frame(y = rnorm(100),
                 x1 = rnorm(100),
                 x2 = rnorm(100),
                 x3 = rnorm(100),
                 x4 = rnorm(100),
                 wg = runif(100,1,100))

ls.form <- list(
  formula(y~x1+x2),
  formula(y~x3+x4),
  formula(y~x1|x2|x3),
  formula(y~x1+x2+x3+x4)
)

我有一个采用不同参数的函数(1-一个子样本,2-一个weights参数的列名,3-一个要尝试的公式列表,以及4-要使用的data.frame)

I have a function that takes different arguments (1- a subsample, 2- a colname for the weights argument, 3- a list of formulas to try and 4- the data.frame to use)

f1 <- function(samp, dat, forms, wgt){
  baselm <- lm(y~x1, data = dat[samp,], weights = dat[samp,wgt])
  lapply(forms, update, object = baselm)
}

如果我调用该函数,则会收到错误消息:

If I call the function, I get an error:

f1(1:66, dat = dd, forms = ls.form, wgt = "wg")
 Error in is.data.frame(data) : object 'dat' not found 

我真的不明白为什么找不到dat对象,它应该是功能环境的一部分.问题出在代码的update部分,就好像您从函数中删除了这行代码一样.

I don't really get why it doesn't find the dat object, it should be part of the fonction environment. The problem is in the update part of the code as if you remove this line from the function, the code works.

最后,将使用lapply

lapply(list(1:66, 33:99), f1, dat=dd, forms = ls.form, wgt="wg")

推荐答案

我认为您的问题归因于lm使用的范围规则,坦率地说,这是r平方的痛苦.

I think your problems are due to the scoping rules used by lm which are quite frankly a pain in the r-squared.

一种选择是使用do.call使其正常工作,但是当它降低输入以给出用于标准打印方法的调用时,您会得到一些难看的输出.

One option is to use do.call to get it to work, but you get some ugly output when it deparses the inputs to give the call used for the standard print method.

f1 <- function(samp, dat, forms, wgt){
  baselm <- do.call(lm,list(formula=y~x1, data = dat[samp,], weights = dat[samp,wgt]))
  lapply(forms, update, object = baselm)
}

一种更好的方法是使用eval(substitute(...))构造,该构造可以提供您最初期望的输出:

A better way is to use an eval(substitute(...)) construct which gives the output you originally expected:

f2 <- function(samp, dat, forms, wgt){
  baselm <- eval(substitute(lm(y~x1, data = dat[samp,], weights = dat[samp,wgt])))
  lapply(forms, update, object = baselm)
}

这篇关于在函数内的lapply中调用update,为什么它不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆