R define dimensions of empty data frame

前端 未结 11 1159
清歌不尽
清歌不尽 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条回答
  •  旧时难觅i
    2020-12-12 22:17

    I have come across the same problem and have a cleaner solution. Instead of creating an empty data.frame you can instead save your data as a named list. Once you have added all results to this list you convert it to a data.frame after.

    For the case of adding features one at a time this works best.

    mylist = list()
    for(column in 1:10) mylist$column = rnorm(10)
    mydf = data.frame(mylist)
    

    For the case of adding rows one at a time this becomes tricky due to mixed types. If all types are the same it is easy.

    mylist = list()
    for(row in 1:10) mylist$row = rnorm(10)
    mydf = data.frame(do.call(rbind, mylist))
    

    I haven't found a simple way to add rows of mixed types. In this case, if you must do it this way, the empty data.frame is probably the best solution.

提交回复
热议问题