如何在R编程的数据帧中使用_for_ [英] How to use _for_ in the dataframes in R programming

查看:76
本文介绍了如何在R编程的数据帧中使用_for_的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 for 循环在R中拟合多个模型.

I'm trying to fit several models in R using the for loop.

我要拟合的数据是R预构建包中的经典 Auto 数据. 让我们发现此数据框的列名称:

The data I want to fit is the classical Auto data in a R pre-build package. Let's discover the names of the columns of this dataframe:

names(Auto)


"mpg"          "cylinders"    "displacement" "horsepower"   "weight"       "acceleration" "year"        
"origin"       "name"   

我想将所有这些预测变量与目标"mpg"一一对应.

I want to fit the all these predictors one by one with the target 'mpg'.

代替:

autotest1 = lm(mpg〜气缸,data = Auto)

autotest1 = lm(mpg~cylinders, data=Auto)

autotest2 = lm(mpg〜displacement,data = Auto)

autotest2 = lm(mpg~displacement, data=Auto)

autotest3 = lm(mpg〜马力,数据=自动)

autotest3 = lm(mpg~horsepower, data=Auto)

autotest4 = lm(mpg〜weight,data = Auto)

autotest4 = lm(mpg~weight, data=Auto)

autotest5 = lm(mpg〜acceleration,data = Auto)

autotest5 = lm(mpg~acceleration, data=Auto)

autotest6 = lm(mpg〜year,data = Auto)

autotest6 = lm(mpg~year, data=Auto)

autotest7 = lm(mpg〜origin,data = Auto)

autotest7 = lm(mpg~origin, data=Auto)

我正在尝试使用 for 循环:

for (var in names(Auto))
{

  cat(lm(mpg~var, data=Auto))

}

Error in model.frame.default(formula = mpg ~ var, data = Auto, drop.unused.levels = TRUE) : 
  variable lengths differ (found for 'var')

我也在尝试将索引i用作 Auto 数据帧的列的Auto [i],但没有成功.有人可以帮助我吗?

I'm also trying Auto[i] with the index i being the columns of Auto dataframe without any success. Anyone could help me?

推荐答案

我们可以使用paste

for(var in names(Auto)) print(lm(paste('mpg ~', var), data = Auto))

或使用reformulate

for(var in names(Auto)) print(lm(reformulate(var, 'mpg'), data = Auto))

这篇关于如何在R编程的数据帧中使用_for_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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