I am trying to create a loop to do linear model, but need some help to do this. I have two dataframe. The subset of first dataframe looks like (i.e. df1)
And the subset of second dataframe looks like (i.e., df2)-
I am trying to do linear model using "BW" by keeping "Time" as co-variate from df1 with "ZX1" of "df2". Same for all the columns of "df2", like ZX2, ZX3.... and do it for "Length", "Sex" and many more from "df1". In the final data frame, I am interested in extracting the p-value only.
So far, what I have done is-
library(purrr)
(results <- map_dbl(1:ncol(df2),
~{
fit <- lm(df2[[.x]] ~ df1$BW * df1$Time)
summary(fit)$coefficients[2,4] #To extract the pvalue
}) |> set_names(1:ncol(df2)))
FINAL <- as.data.frame(results)
names(FINAL) <- "BW"
Same for other, that is Length
(results <- map_dbl(1:ncol(df2),
~{
fit <- lm(df2[[.x]] ~ df1$Length * df1$Time)
summary(fit)$coefficients[2,4] #To extract the pvalue
}) |> set_names(1:ncol(df2)))
results <- as.data.frame(results)
FINAL <- cbind(FINAL, results)
colnames(FINAL)[2] <- "Length"
Same for others, that is Sex
(results <- map_dbl(1:ncol(df2),
~{
fit <- lm(df2[[.x]] ~ df1$Sex * df1$Time)
summary(fit)$coefficients[2,4] #To extract the pvalue
}) |> set_names(1:ncol(df2)))
results <- as.data.frame(results)
FINAL <- cbind(FINAL, results)
colnames(FINAL)[3] <- "Sex"
This is the final dataframe, that I wanted. Is there a way to do it all together and save the p-values in a final dataframe instead of doing it one by one?