167
  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?

1
  • 1
    If you want to create an empty data.frame with dynamic names (colnames in a variable), this can help: names <- c("v","u","w") df <- data.frame() for (k in names) df[[k]]<-as.numeric() You can change the type as well if you need so. Commented Mar 3, 2017 at 20:11

1 Answer 1

414

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"))))
Sign up to request clarification or add additional context in comments.

6 Comments

hello, do you have an easy way to add columns (type = character) which colnames are ``` new_col_names <- c("new1", "new2") ``` ? I tried this : ``` df[, new_col_names ] <- NULL ``` , this doesn't work
@DDchen If you have a dataframe df, this should work df[new_col_names] <- NA_character_
setNames(data.frame(matrix(ncol = length(col), nrow = 0)), col <- c("name", "age", "gender")) for a more dynamic way of doing it
@Julien Isn't assigning a variable within the context of another function call considered bad practice in R? Do we know that the second argument is always evaluated before the first is called?
Good question, it's indeed risky. But it does work here
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.