如果另一個問題中已經有可用的解決方案,我深表歉意。我有 500 多個 csv 檔案,所有檔案都具有順序名稱“name1、name2 等”。我需要對每個檔案運行相同的簡單線性回歸并保存系數輸出。每個檔案的列名也相同,并且只有一個單一的 x 和 y 變數。
我只知道怎么用
lm(tablename$columnY~tablename$columnX)
在單個檔案上。我不確定如何設定一個回圈來遍歷每個檔案。
任何幫助表示贊賞
uj5u.com熱心網友回復:
這是我使用函式運行它的方法,(您也可以使用 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494964.html
上一篇:如何在Python中提供列標題
