Hello coders,
I have the following data frame:
d <- structure(list(Group = c("A", "A", "A", "A", "A", "B", "B", "B",
"B", "B", "C", "C", "C", "C", "C", "D", "D", "D", "D", "D"),
D = c(0.1, 0.2, 0.2, 0.1, 0.1, 0.5, 0.5, 0.1, 0.1, 0.5, 0.1,
0.5, 0.5, 0.1, 0.5, 0.1, 0.5, 0.5, 0.1, 0.5), LF = c(8.4368504387337,
8.47470313979528, 8.38640090116621, 6.06181547038399, 6.19275193549284,
5.9648638653108, 6.18325202989082, 6.77963777620169, 5.88425046280083,
6.30863403147467, 5.96856546407038, 6.43276144155514, 6.33398985544227,
7.5847730776122, 5.75127309348355, 5.78970529642155, 5.99057129113077,
5.85363823020058, 6.14846829591765, 6.22689592921589)), row.names = c(NA,
-20L), class = "data.frame")
Fo each group (A-D) in dataframe d
, I would like to take a linear regression of columns LF
and D
. Then, I want to store the following values from the summary of the model into columns called r2
and Kd
:
lm <- lm(d$LF ~ d$D)
summary <- summary(lm)
r2 <- summary$r.squared
Kd <- summary$coefficients[2,1]
Does anyone know how to iterate this over each group in the data frame? I'm sure group_by
and lapply
would work in this situation, but I'm having trouble with the syntax. Each group will have repeating values for r2
and Kd
and that's fine.
Thanks so much for any help you can provide!