Mark Heckmann Mark Heckmann - 1 year ago 42
R Question

Error when adding columns with default values to dataframe with zero rows

Why does this work,

# add ONE column to dataframe with zero rows

x <- data.frame(a=character(0))
x["b"] <- character(0)

while this does not?

# add SEVERAL columns to dataframe with zero rows

x <- data.frame(a=character(0))
x[c("b", "c")] <- character(0)

error in value[[jvseq[[jjj]]]] : index out of limits [... freely translated]

Note, that this is perfectly okay, if we have non-zero rows.

x <- data.frame(a=1)
x["b"] <- NA

x <- data.frame(a=1)
x[c("b", "c")] <- NA

And what would be a simple alternative to add multiple columns to zero row dataframes?

Answer Source

From help("[.data.frame"):

Data frames can be indexed in several modes. When [ and [[ are used with a single vector index (x[i] or x[[i]]), they index the data frame as if it were a list.

From help("["):

Recursive (list-like) objects

Indexing by [ is similar to atomic vectors and selects a list of the specified element(s).

Thus, you need to do pass a list (or data.frame):

x <- data.frame(a=character(0))
x[c("b", "c")] <- list(character(0), character(0))
#'data.frame':  0 obs. of  3 variables:
# $ a: Factor w/ 0 levels: 
# $ b: chr 
# $ c: chr