Create empty data frame with column names by assigning a string vector?

RDataframe

R Problem Overview


  1. Create an empty data frame:
y <- data.frame()
  1. Assign x, a string vector, to y as its column names:
    x <- c("name", "age", "gender")
    colnames(y) <- x

Result:

>Error in colnames<-(*tmp*, value = c("name", "age", "gender")) : 'names' attribute [3] must be the same length as the vector [0]

Actually, the x length is dynamic, so

y <- data.frame(name=character(), age=numeric(), gender=logical())

is not an efficient way to name the column. How can I solve the problem?

R Solutions


Solution 1 - R

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)

Or

data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEric ChangView Question on Stackoverflow
Solution 1 - RRonak ShahView Answer on Stackoverflow