本文介绍了在公式中显示字符串,而不在lm fit中显示为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法解决执行lm(sformula)时未显示分配给sformula的字符串的问题.我感觉这是R处理函数参数的通用方式,而不是线性回归所特有的.

I am not able to resolve the issue that when lm(sformula) is executed, it does not show the string that is assigned to sformula. I have a feeling it is generic way R handles argument of a function and not specific to linear regression.

下面是通过示例说明问题的方法.示例1具有不需要的输出lm(formula = sformula).示例2是我想要的输出,即lm(formula = "y~x").

Below is the illustration of the issue through examples. Example 1, has the undesired output lm(formula = sformula). The example 2 is the output I would like i.e., lm(formula = "y~x").

x <- 1:10
y <- x * runif(10)
sformula <- "y~x"

## Example: 1 
lm(sformula)

## Call:
## lm(formula = sformula)

## Example: 2
lm("y~x")

## Call:
## lm(formula = "y~x")

推荐答案

eval(call("lm", sformula))怎么样?

lm(sformula)
#Call:
#lm(formula = sformula)

eval(call("lm", sformula))
#Call:
#lm(formula = "y~x")

通常来说,lm有一个data自变量.让我们开始吧:

Generally speaking there is a data argument for lm. Let's do:

mydata <- data.frame(y = y, x = x)
eval(call("lm", sformula, quote(mydata)))
#Call:
#lm(formula = "y~x", data = mydata)


上面的call() + eval()组合可以替换为do.call():


The above call() + eval() combination can be replaced by do.call():

do.call("lm", list(formula = sformula))
#Call:
#lm(formula = "y~x")

do.call("lm", list(formula = sformula, data = quote(mydata)))
#Call:
#lm(formula = "y~x", data = mydata)

这篇关于在公式中显示字符串,而不在lm fit中显示为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 07:38