简体   繁体   中英

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

 }

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