Jeppe Olsen
Jeppe Olsen

Reputation: 1008

Add data to data.frame with 0 rows

Consider this:

df <- data.frame(a=1:2, b=3:4)

I can add a new column and assign values to it like this:

df$c <- 5

But if I subset this, so its an empty data.frame and try to assign anything to it, it will return an error:

df2 <- subset(df, a==3)
df2$d <- 10

Error in $<-.data.frame(tmp, "d", value = 10) : replacement has 1 row, data has 0

This will stop loops, so my question is if there are other ways to assign values to a column in a dataframe that does not return errors when the dataframe is empty?

Upvotes: 1

Views: 3740

Answers (2)

ztl
ztl

Reputation: 2602

You can achieve this in one line with dplyr by subsetting the data.frame with filter and then adding a new column with mutate. It won't crash whether your subsetting operation (filter here) results in an empty data.frame or not:

library(dplyr)
df <- data.frame(a=1:2, b=3:4)
df2 <- df %>% filter(a==3) %>% mutate(d=10)
# [1] a b d
# <0 rows> (or 0-length row.names)

Upvotes: 1

Uwe
Uwe

Reputation: 42592

If the intent of the OP is to create an empty data.frame with an additional column you may try:

df2$d <- integer(0)
df2
#[1] a b c d
#<0 rows> (or 0-length row.names)

However, this could have been done in the initial call to data.frame as well:

data.frame(a = integer(0), b = integer(0), c = integer(0), d = integer(0))
#[1] a b c d
#<0 rows> (or 0-length row.names)

Upvotes: 2

Related Questions