Create an empty data.frame

前端 未结 17 1143
猫巷女王i
猫巷女王i 2020-11-22 16:06

I\'m trying to initialize a data.frame without any rows. Basically, I want to specify the data types for each column and name them, but not have any rows created as a result

17条回答
  •  天命终不由人
    2020-11-22 16:27

    This question didn't specifically address my concerns (outlined here) but in case anyone wants to do this with a parameterized number of columns and no coercion:

    > require(dplyr)
    > dbNames <- c('a','b','c','d')
    > emptyTableOut <- 
        data.frame(
            character(), 
            matrix(integer(), ncol = 3, nrow = 0), stringsAsFactors = FALSE
        ) %>% 
        setNames(nm = c(dbNames))
    > glimpse(emptyTableOut)
    Observations: 0
    Variables: 4
    $ a  
    $ b  
    $ c  
    $ d 
    

    As divibisan states on the linked question,

    ...the reason [coercion] occurs [when cbinding matrices and their constituent types] is that a matrix can only have a single data type. When you cbind 2 matrices, the result is still a matrix and so the variables are all coerced into a single type before converting to a data.frame

提交回复
热议问题