R define dimensions of empty data frame

前端 未结 11 1153
清歌不尽
清歌不尽 2020-12-12 21:34

I am trying to collect some data from multiple subsets of a data set and need to create a data frame to collect the results. My problem is don\'t know how to create an empt

11条回答
  •  情深已故
    2020-12-12 22:29

    You can do something like:

    N <- 10
    collect1 <- data.frame(id   = integer(N),
                           max1 = numeric(N),
                           min1 = numeric(N))
    

    Now be careful that in the rest of your code, you forgot to use the row index for filling the data.frame row by row. It should be:

    for(i in seq_len(N)){
       collect1$id[i] <- i
       ss1 <- subset(df1, df1$id == i)
       collect1$max1[i] <- max(ss1$value)
       collect1$min1[i] <- min(ss1$value)
    }
    

    Finally, I would say that there are many alternatives for doing what you are trying to accomplish, some would be much more efficient and use a lot less typing. You could for example look at the aggregate function, or ddply from the plyr package.

提交回复
热议问题