0

How i can create empty dataframe with column name where column is a vector any length

c("A","B","C")

Im try

df<-data.frame()
colnames(df)<-c("A","B")

But is not working

10
  • 4
    Why do you need an empty data.frame? You can do this: df <- data.frame(A = numeric(n), B = character(n), C = logical(n)) for any n. Commented Oct 21, 2015 at 9:03
  • data.frame(A = c(), B = c()) Commented Oct 21, 2015 at 9:03
  • 4
    @RonakShah Have you checked the output? Commented Oct 21, 2015 at 9:03
  • As @Roland said, you will virtually never need to do something similar. Commented Oct 21, 2015 at 9:04
  • 1
    But, it also doesn't show any names, i.e. the OP wanted to have A, B in the output as columns, here you have 0 variables and 0 observations. str(data.frame(A = c(), B = c())) 'data.frame': 0 obs. of 0 variables Commented Oct 21, 2015 at 9:07

2 Answers 2

11
x <- LETTERS[1:3]
df <- as.data.frame(matrix(,0,length(x)))
names(df) <- x

str(df)
# 'data.frame': 0 obs. of  3 variables:
#  $ A: logi 
#  $ B: logi 
#  $ C: logi 

With OP's vector:

x <- c("field1","field2", "field3")
df <- as.data.frame(matrix(,0,length(x)))
names(df) <- x
str(df)
# 'data.frame': 0 obs. of  3 variables:
#  $ field1: logi 
#  $ field2: logi 
#  $ field3: logi 
Sign up to request clarification or add additional context in comments.

8 Comments

For example im have vector c("field1","field2, filed3")
With a line: as.data.frame(matrix(nrow=0,ncol=length(x),dimnames=list(NULL,x)))
I believe that there are cases where this can be useful. Imagine for example the case where you want to generate a table (dataframe) where each row is the result of calculations performed on temporary data retrieved from an external source. In such a situation you may not know at the beginning the number of rows that your resulting data frame will have. I think that rbinding each row, starting with an empty dataframe with named columns, would make sense there.
@RHertel No, guess a reasonable size, (over-)allocate that, grow in chunks only if needed, subset to the final size in the end.
@RHertel If you know the number of iterations (as one usually does), you allocate a list before in which you put the data.frame returned from the external source. At the end of the loop, you rbind them all together with do.call. Or do like Roland suggested.
|
6

You can try this:

df1 <- data.frame(matrix(vector(),ncol=3))
colnames(df1) <-c("A","B","C")
df1
#[1] A B C
#<0 rows> (or 0-length row.names)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.