1

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
  • 27,591
  • 71
  • 194
  • 314

2 Answers2

1

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
  • 789,025
  • 32
  • 460
  • 575
1

This will also do:

df <- as.data.frame(matrix(rep(NA, length(names)), nrow=1))
names(df) <- names
Sandipan Dey
  • 19,788
  • 2
  • 37
  • 54