Adrian
Adrian

Reputation: 9793

R: creating a data.frame with NULL values

I want to have NULL values in my data.frame (not NA). And the following doesn't seem to work.

> data.frame(x = c(1, 2, 3), y = c(NULL, NULL, NULL))
Error in data.frame(x = c(1, 2, 3), y = c(NULL, NULL, NULL)) : 
  arguments imply differing number of rows: 3, 0

My goal is to output my data.frame into a .csv file, and the cells with the NULL values should be blank.

Upvotes: 4

Views: 8959

Answers (1)

Albert Ziegler
Albert Ziegler

Reputation: 71

You can get the dataframe with NULL entries using:

> data.frame(x = c(1, 2, 3), y = I(list(NULL, NULL, NULL))


Explanation:

If you want to use data.frame to include columns that are constantly NULL, you need to protect them using I.

You also have to input a list rather than a c of NULLs. That's because c(NULL, NULL, NULL) is identical to NULL -- NULLs can't be concatenated. Nor can they be elements of a vector, so every column that contains NULL values needs to be a list rather than a vector.

Using write.table and similar functions will call as.character on the column full of NULLs, writing the string "NULL" in the null cell. If you don't want that behaviour, it's probably best to use empty strings instead of NULLs.

Upvotes: 7

Related Questions