speendo
speendo

Reputation: 13345

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

Upvotes: 22

Views: 18631

Answers (2)

Richie Cotton
Richie Cotton

Reputation: 121127

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

library(dplyr)
cars |> filter(FALSE)

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

cars |> mutate(across(everything(), \(x) NA))

Upvotes: 41

InColorado
InColorado

Reputation: 348

Or a 2-step version

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

Upvotes: 1

Related Questions