5

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.

10
  • 3
    Perhaps data.frame(x = c(1, 2, 3), y = ""). Commented Nov 20, 2017 at 22:21
  • 1
    d <- data.frame(x=1:3); d$y <- replicate(3, NULL) Commented Nov 20, 2017 at 22:23
  • @Masoud But if you save that data frame to a CSV file, it looks blank on column y. I think it depends on what Adrian needs. Commented Nov 20, 2017 at 22:25
  • 5
    Why NULLs? What to you plan on storing in there? Generally you can't have collections of NULL values in R. Use NA values and write.table() allows you to control how those values are rendered: na = "NA" Commented Nov 20, 2017 at 22:25
  • 1
    In general, having literal NULL values within a data.frame is really problematic. I think the more appropriate question to be asking (and you did) is "how to get empty values in a CSV". Commented Nov 20, 2017 at 22:25

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.