开发者

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

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 column names, the same number of rows but without any data in开发者_如何学Pythonside.


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)


Or a 2-step version

 new.df <- cars
 new.df[] <- NA
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜