I have the following data frame
Year ID V1
2000 1 4
2000 2 1
2000 3 2
2001 1 3
2001 2 1
2001 3 5
.....
I have a function that takes the above data frame and a year value, performs a regression (V1 against ID), and returns a data frame containing the fitted coefficients for each ID for that year:
ID Coeff
1 4
2 1
3 2
.....
I would like to run the above function for a set of year values, extract the ID and its corresponding fitted coefficients for that year, and bind them into a data frame:
Year ID Coeff
2000 1 4
2000 2 1
2000 3 2
2001 1 3
2001 2 1
2001 3 5
.....
I can do the above with a for loop but I'm wondering if there's a better alternative (using dplyr or something else).
Edit:
data(iris)
set.seed(2)
iris$Sepal.Length <- as.factor(iris$Sepal.Length)
iris$Sepal.Width <- as.factor(iris$Sepal.Width)
iris$Random <- sample(0:1, size = nrow(iris), replace = TRUE)
fit_function <- function(df, Species) {
fit <- glm(Random ~ -1+Sepal.Length + Sepal.Width,
data = df[df$Species == Species,],
family = "binomial")
final_df <- data.frame(Species = Species, Name = names(coef(fit)), Coef = unname(coef(fit)))
return(final_df)
}
all <- c()
for (i in unique(as.character(iris$Species))) {
all <- rbind(all, fit_function(iris, i))
}