I wrote a function that runs a linear model and outputs a data frame. I would like to run the function several times over two grouping variables and stack the output. Here is a hypothetical dataset and function:
data = data.frame(grade_level = rep(1:4, each = 3),
x = rnorm(12, mean = 21, sd = 7.5),
y = rnorm(12, mean = 20, sd = 7),
cut_set = rep(c("low", "med", "high"), each = 4))
func = function(grade, set){
model = lm(y ~ x, data=data[data$grade_level == grade & data$cut_set == set,])
fitted.values = model$fitted.values
final = data.frame(grade_level = data$grade_level[data$grade_level == grade & data$cut_set == set],
predicted_values = fitted.values)
final
}
I can run it multiple times and then bind the output but I know this isn't the best
g1.low <- func(grade = 1, set = "low")
g1.med <- func(grade = 1, set = "med")
pred.values = rbind(g1.low, g1.med)
I would like to loop through all grades (1 to 4) and set ("low", "med", "high") values. I've tried this loop but it doesn't work. I wonder if there is a purrr solution.
for (i in grades) {
for(c in 1:length(cut_sets)) {
temp <- func(grade = i, set = cut_sets[c])
predicted.values <- rbind(predicted.values, temp)
}
}