How to copy an object's structure (but not the data)

前端 未结 1 1424
情歌与酒
情歌与酒 2021-02-05 10:21

How do I copy an object\'s specifications, but not the data?

In my specific case I have a data frame and I want another data frame with the same column classes, the same

1条回答
  •  走了就别回头了
    2021-02-05 11:04

    You can't have no data and the same number of rows. If you want no data then select the zeroth row. For example, with the cars dataset

    cars[0, ]
    

    or

    subset(cars, FALSE)
    

    If you want the same number of rows, then set the data values to be NA.

    as.data.frame(lapply(cars, function(x) rep.int(NA, length(x))))
    

    Or using dplyr:

    library(dplyr)
    f <- function(x) NA
    cars %>% mutate_all(f)
    

    0 讨论(0)
提交回复
热议问题