如何在R中将矢量值用作变量

时间:2017-06-06 11:44:38

标签: r regression linear-regression

我有一个名为repay的数据框,我已经为我感兴趣的变量变量名称创建了一个向量。

[{"sample1":{"t":"{a={b=1},c={d=2}}"}, "sample2" : "something"}]

我想编写一个for循环,对变量中的每个变量进行一些单变量分析。例如:

variables<-names(repay)[22:36]

但是,它不会将for (i in 1:length(variables)) { model<-glm(Successful~ variables[i] ,data=repay ,family=binomial(link='logit')) } 识别为变量,并显示以下错误消息:

  

model.frame.default中的错误(公式=成功〜变量[i],数据   = repay,:变量长度不同(找到&#39;变量[i]&#39;)

4 个答案:

答案 0 :(得分:0)

您可以从字符串

创建语言对象
var = "cyl"
lm(as.formula(sprintf("mpg ~ %s", var)), data=mtcars)
# alternative (see also substitute)
lm(bquote(mpg~.(as.name(var))), data=mtcars)

答案 1 :(得分:0)

或者,您可以在变量的模型中使用To: {my $user = new RT::User($RT::SystemUser); $user->Load($Transaction->OldValue); $user->EmailAddress() || $Transaction->OldValue} Subject: [{$rtname } #{ $Ticket->Id() }] Stolen: { $Ticket->Subject() } URL: https://rt.example.com/rt/Ticket/Display.html?id={ $Ticket->id } A ticket you owned: { $Ticket->Subject() } has been taken by {$Ticket->OwnerObj->RealName} <{$Ticket->OwnerObj->EmailAddress}>. 屈服。 让我们考虑一下

assign

屈服:

repay<-data.table(Successful=runif(10),a=sample(10),b=sample(10),c=runif(10))
variables<-names(repay)[2:4]

然后你可以执行循环

>repay Successful a b c 1: 0.8457686 7 9 0.2930537 2: 0.4050198 6 6 0.5948573 3: 0.1994583 2 8 0.4198423 4: 0.1471735 1 5 0.5906494 5: 0.7765083 8 10 0.7933327 6: 0.6503692 9 4 0.4262896 7: 0.2449512 4 1 0.7311928 8: 0.6754966 3 3 0.4723299 9: 0.7792951 10 7 0.9101495 10: 0.6281890 5 2 0.9215107

产生3个对象:for (i in 1:length(variables)){ assign(paste0("model",i),eval(parse(text=paste("glm(Successful~",variables[i],",data=repay,family=binomial(link='logit'))")))) }model1model2

model3

同意 >model1 Call: glm(formula = Successful ~ a, family = binomial(link = "logit"), data = repay) Coefficients: (Intercept) a -0.36770 0.05501 Degrees of Freedom: 9 Total (i.e. Null); 8 Residual Null Deviance: 5.752 Residual Deviance: 5.69 AIC: 17.66 model2 et.c。

答案 2 :(得分:0)

可能有用的小解决方法

 for (i in 22:36) 
{
  ivar <- repay[i] #choose variable for running the model
  repay2 <- data.frame(Successful= repay$Successful, ivar) #create new data frame with 2 variables only for running the model

  #run model for new data frame repay2
  model<-glm(Successful~ ivar
             ,data=repay2
             ,family=binomial(link='logit'))
}

答案 3 :(得分:0)

尝试使用R中的formula函数。它将允许正确解释模型,如下所示:

for (i in 1:length(variables){
    myglm <- glm(formula(paste("Successful", "~", variables[i])),
                 data = repay, family = binomial(link = 'logit'))

有关在此上下文中可以执行的更多操作,请参阅my post here