2

I have a list of column names, such as

names = c("a","b")

I'd like to make an empty data frame with the column names taken from names, with 1 row where all values are NA.

"a"  "b"
NA    NA

I've tried something like this:

d = data.frame()
for(i in seq(1,length(names))) {
d[,toString(names[i])] = NA
}

Doesn't seem to work

CodeGuy
  • 28,427
  • 76
  • 200
  • 317

2 Answers2

2

We can replicate NA by the length of names into a list, set the names of the list with names and convert to a data.frame

data.frame(setNames(rep(list(NA), length(names)), names))

Or another option is read.csv

read.csv(text=paste(rep(NA, length(names)), collapse=","), 
                   header=FALSE,col.names = names)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

This will also do:

df <- as.data.frame(matrix(rep(NA, length(names)), nrow=1))
names(df) <- names
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63