【问题标题】:How to perform linear regression between one column and all other columns in a data frame and save r squared values in new data frame?如何在数据框中的一列和所有其他列之间执行线性回归并将 r 平方值保存在新数据框中?
【发布时间】:2019-11-26 22:08:56
【问题描述】:

我正在尝试测试我的数据框中的一列 (CS.1) 中的数据与数据框中的其余列 (allree) 的相似程度。数据框有 283 列,第一个包含观察的标签。我尝试设置一个 for 循环来执行线性回归并将 r 平方值与列名一起保存在新数据框中。但是,我不断收到与数据框相邻的错误,因为结果的长度不正确。

这是代码:

#this is the data frame
allree<-read.csv("All REE 2.csv")

#creating the data frame for the results
cs1 <- data.frame(row = 1:280)
dat <- data.frame(rsq = 1:3, samp = 1:3)

#trying to test each column against the second column (CS.1) and save the r-squared values
for(x in 3:283){
  na.rm=TRUE
  reg<-lm(CS.1~allree[,x], data=allree)
  rsq<-summary(reg)$r.squared
  dat$r2[x] <- rsq
  dat$sample[x] <- colnames(allree)[x]
  if(x==3) cs1<-dat
  if(x>3)cs1<-rbind(cs1, dat)
  }

这是错误:

Error in `$<-.data.frame`(`*tmp*`, "r2", value = c(NA, NA, 0.180399384405891, : replacement has 4 rows, data has 3

我需要将原始数据分成多个数据框吗?如果我能以这种方式弄清楚,我想对其他几列重复这个测试。

【问题讨论】:

  • 如果您只想查看 r-squared 值,您可以只取相关矩阵并将所有元素平方,即cor(your_data)^2,因为对于单变量回归,r-squared 只是相关性, r, 平方。如果您只想查看回归与单个变量的 r 平方,您只需从相关矩阵中选择该变量的列。

标签: r loops linear-regression repeat


【解决方案1】:

由于您没有提供可重现的示例,我将使用 mtcars 数据框来完成。

我将使用 purrrbroomdplyr 包形式的函数,而不是使用 for 循环。

数据

这个数据框默认出现在R中

glimse(mtcars)
Observations: 32
Variables: 11
$ mpg  <dbl> 21.0, 21.0, 22.8, 21.4, …
$ cyl  <dbl> 6, 6, 4, 6, 8, 6, 8, 4, …
$ disp <dbl> 160.0, 160.0, 108.0, 258…
$ hp   <dbl> 110, 110, 93, 110, 175, …
$ drat <dbl> 3.90, 3.90, 3.85, 3.08, …
$ wt   <dbl> 2.620, 2.875, 2.320, 3.2…
$ qsec <dbl> 16.46, 17.02, 18.61, 19.…
$ vs   <dbl> 0, 0, 1, 1, 0, 1, 0, 1, …
$ am   <dbl> 1, 1, 1, 0, 0, 0, 0, 0, …
$ gear <dbl> 4, 4, 4, 3, 3, 3, 3, 4, …
$ carb <dbl> 4, 4, 1, 1, 2, 1, 4, 2, …

代码

# Map function from purrr allow you to do a loop
purrr::map(

  # set the elements to iterate over.
  # in this case all variables except 
  # the first (mpg)
  mtcars[,-1],

  # The second argument is the body of the loop. 
  # An lm call with the formula as follow.
  # here the .x is replace by a new variable 
  # in each iteration
  ~lm(mpg ~ .x, data = mtcars)
  ) %>%

  # Then summarise each output with broom::glance
  purrr::map(broom::glance) %>%

  # bind all summary
  dplyr::bind_rows(.id = "variable") %>%

  # selecting the variables of interest
  dplyr::select(variable, r.squared)

# A tibble: 10 x 2
   variable r.squared
   <chr>        <dbl>
 1 cyl          0.726
 2 disp         0.718
 3 hp           0.602
 4 drat         0.464
 5 wt           0.753
 6 qsec         0.175
 7 vs           0.441
 8 am           0.360
 9 gear         0.231
10 carb         0.304

【讨论】:

    猜你喜欢
    • 2020-03-15
    • 2021-08-02
    • 1970-01-01
    • 2014-11-25
    • 2022-08-13
    • 1970-01-01
    • 2016-04-25
    • 2021-01-06
    • 1970-01-01
    相关资源
    最近更新 更多