Create an empty data.frame

前端 未结 17 1076
猫巷女王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:12

    If you already have a dataframe, you can extract the metadata (column names and types) from a dataframe (e.g. if you are controlling a BUG which is only triggered with certain inputs and need a empty dummy Dataframe):

    colums_and_types <- sapply(df, class)
    
    # prints: "c('col1', 'col2')"
    print(dput(as.character(names(colums_and_types))))
    
    # prints: "c('integer', 'factor')"
    dput(as.character(as.vector(colums_and_types)))
    

    And then use the read.table to create the empty dataframe

    read.table(text = "",
       colClasses = c('integer', 'factor'),
       col.names = c('col1', 'col2'))
    

提交回复
热议问题