0

My dataframe is like:

  samples.L samples.T      le.1      le.2      le.3      le.4      le.5
         10       1.0  9.683726  9.691982  9.704387  9.719390  9.735400
         10       3.5  9.828530  9.829962  9.832273  9.835296  9.838709
         25       1.0 24.675467 24.677010 24.679439 24.682560 24.685718
         25       3.5 24.822328 24.822601 24.823026 24.823410 24.823209

Now I want to operate linear regression between independent variables samples.L and samples.T and respectively each respond variables le.? (?=1,2,3,4,5), so that I could get 5 models ?

How could I use apply family function or other method to realize it?

dawei
  • 57
  • 1
  • 7

1 Answers1

0

You can create a function that fits a linear model of the other variables in terms of samples.L and samples.T.

lm_func <- function(y) lm(y ~ samples.L + samples.T, data = data)

You can then use lapply() to apply this function to each of the desired columns.

lapply(data[,3:6], lm_func)

Additionally, you can use the tidyverse packages with the broom package to simplify your outputs.

library(tidyverse)
library(broom)
map_dfr(data[,3:6], function(x) summary(lm_func(x)) %>% glance()) 
map_dfr(data[,3:6], function(x) summary(lm_func(x)) %>% tidy())

Better yet, you can do the following.

fit <- lm(cbind(le.1, le.2, le.3, le.4) ~ samples.L + samples.T, data = data)
summary(fit) %>% map_dfr(glance)
summary(fit) %>% map_dfr(tidy)
hpesoj626
  • 3,529
  • 1
  • 17
  • 25