简体   繁体   中英

Loop through function and stack the output into a dataset in R

I wrote a function that runs a linear model and outputs a data frame. I would like to run the function several times 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)) 

func = function(grade){
  model = lm(y ~ x, data=data[data$grade_level == grade,])
  fitted.values = model$fitted.values 
  final = data.frame(grade_level = data$grade_level[data$grade_level == grade],
                     predicted_values = fitted.values)
  final
  }

Currently, I run the function over each grade in the dataset:

grade1 = func(1)
grade2 = func(2)
grade3 = func(3)
grade4 = func(4)

pred.values = rbind(grade1, grade2, grade3, grade4)

How can I use a loop (or something else) to more efficiently run this function multiple times?

The purrr package has a really handy function for this. map works like the apply family of functions in Base R (which operate like a for loop in many ways). The _dfr specifies that you want to call rbind on the results before returrning.

This function says: "loop through c(1, 2, 3, 4) , each time calling func() on each, then rbind the results at the end and give the data.frame back to me."

purrr::map_dfr(1:4, func)

Please find a solution using a loop an rbind below.

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)) 

func = function(grade){
  model = lm(y ~ x, data=data[data$grade_level == grade,])
  fitted.values = model$fitted.values 
  final = data.frame(grade_level = data$grade_level[data$grade_level == grade],
                     predicted_values = fitted.values)
  return(final)
}

grades <- c(1:4)

pred.values <- data.frame()
for (i in grades) {
  
  temp <- func(grade = i)
  pred.values <- rbind(pred.values, temp)
  
}

Will give

> pred.values
   grade_level predicted_values
1            1         30.78802
2            1         22.79665
3            1         29.56155
4            2         14.60050
5            2         14.56934
6            2         14.71737
7            3         16.97698
8            3         17.71697
9            3         18.95596
10           4         15.18937
11           4         16.56399
12           4         22.49093

A solution using lapply()

 do.call("rbind", lapply(1:4, func))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM