简体   繁体   中英

How to use apply or lapply function

I have columns of data and would like to use the WD as an independent variable and E1-E14 as dependent variable and do a regression for each and write the output to a csv file. Please help enter image description here

This what I did, however it outputs the same results for all columns. I think the mod variable is being incorrectly set.

mod <- function(y) lm(E1 ~ WD , data = data)
lapply(data[,5:16], mod) 

This is probably what you want, but it may requires some changes to get to the full extent of what you need.

df <- data.frame(WD = c(1,1,0,0,0,1,1,1,0,0),
                E1 = rnorm(10,0,1),
                E2 = rnorm(10,0,1))


mod <- function(x){

  lm(WD ~ x, data = df)


}

sapply(df[setdiff(names(df),"WD")],mod)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM