Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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 inside.

like image 663
speendo Avatar asked Jul 20 '11 15:07

speendo


1 Answers

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)
like image 175
Richie Cotton Avatar answered Oct 05 '22 16:10

Richie Cotton