Search code examples
rfunctionloopsglm

Create a for function that stores the output in a data frame in R


I need to save the output of this loop in a data.frame. How can I do it? I have seen some questions alike, but I couldn't reproduce them.

lapply could work?

library(dplyr)

sex <- rbinom(50,1,.5)
positive <- rbinom(50,1,.3)
age <- c(1:10,5:15,5:10,1:10,16:26,16,26)
DF <- data.frame(sex,positive,age)


    for (i in 1:26) {
  pos.by.age <- glm(positive ~1
                       , data=(filter(DF, age==i)), family=poisson)
  coolfunction <- function(x) {as.character(c(round(exp(coef(x)
[1])*100,2)))}
   print(c(i,coolfunction(pos.by.age),nrow(filter(DF, 
age==i,positive==1)),nrow(filter(DF, age==i))))
 }

Solution

  • # create an empty data frame
    df <- data.frame(matrix(NA, ncol = 4, nrow = 1))
    In <- c(15:68,70:77,79,80,81)
    
    for (i in 1: length(In)) {
    
      int <- In[i]
    
      pos.by.age <- glm(positive ~1, data=(filter(DF, age==int)), family=poisson)
    
      df[i, ] <- c(int, coolfunction(pos.by.age), nrow(filter(DF,age==int,positive==1)), nrow(filter(DF, age==int)))
    
     }