2

I have to create a new dataframe from a data frame that I don't know apriori.

The new dataframe should have the same structure as the old, but it should be empty.

Example

Let's suppose that the old data frame is the following:

> c1 = c(1,2,3)
> c2 = c("str1", "str2", "str3")
> c3 = c(3.2, 2.4, 5.6)
> m <- data.frame(c1,c2,c3)
> m
  c1   c2  c3
1  1 str1 3.2
2  2 str2 2.4
3  3 str3 5.6
> names(m) <- c("var1", "var2", "var3")
> m
  var1 var2 var3
1    1 str1  3.2
2    2 str2  2.4
3    3 str3  5.6

The new data frame should be like this:

newDat <- data.frame("var1" = as.numeric(), "var2" = as.character(), "var3" = as.numeric())

The point is that I don't know how the existing data frame (m) is made

1 Answer 1

6

Just take no rows from the original data frame:

> testDat = m[FALSE,]

There is a slight difference between that and your newDat example, because my testDat has a factor column which still has the levels from the original factor:

> str(testDat)
'data.frame':   0 obs. of  3 variables:
 $ var1: num 
 $ var2: Factor w/ 3 levels "str1","str2",..: 
 $ var3: num 

If that's not a problem then job done, if it is a problem then you probably need to loop over the variables and reset any factors...

Sign up to request clarification or add additional context in comments.

1 Comment

..or just use m <- data.frame(c1,c2,c3, stringsAsFactors = FALSE) in your old dataframe. Then using @Spacedman solution you will maintain the character class for testDat$var2 object. But this of course depends on your real dataset

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.