簡體   English   中英

R中的線性回歸,遍歷csv文件

[英]Linear regression in R, loop through csv files

如果另一個問題中已經有可用的解決方案,我深表歉意。 我有 500 多個 csv 文件,所有文件都具有順序名稱“name1、name2 等”。 我需要對每個文件運行相同的簡單線性回歸並保存系數輸出。 每個文件的列名也相同,並且只有一個單一的 x 和 y 變量。

我只知道怎么用

lm(tablename$columnY~tablename$columnX)   

在單個文件上。 我不確定如何設置一個循環來遍歷每個文件。

任何幫助表示贊賞

這是我使用函數運行它的方法,(您也可以使用 for 循環)。 原則是命名所有有問題的文件並一個一個地瀏覽它們,邊走邊保存每個模型的結果。

#put all your files in one folder and point to the folder path
path <- "C:/Users/xxx/Desktop"

#list all the files, with directory attached
lst <- list.files(path, full.names = T)

#make a function or loop (i like functions to get structured output)
fun <- function(i){
  
  #read each csv one at a time
  dat <- read.csv(lst[i])
  
  #make the model
  mod <- lm(dat$columnY~dat$columnX)
  
  #extract the information from the model (press view on any model and chose the desired values and hjust copy that code)
  intcpt <- mod[["coefficients"]][["(Intercept)"]]
  y <- mod[["coefficients"]][["columnX"]]
  
  #set into dataframe, with the name of the file
  out <- data.frame(lst[i], intcpt, y)
}
temp <- lapply(1:length(lst), fun) #run the model (will take the last thing stated in the fuction and make a list elemnt for each "loop")
results <- do.call("rbind",temp) #from list to dataframe

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM