zesla
zesla

Reputation: 11833

how to add one-row columns into empty dataframe in r

I have a tryCatch block that returns a dataframe. In some cases, it returns a empty dataframe with 0 rows. No matter it's empty or not, I need to add some data in there. (some columns with one row). I found when it returns an empty dataframe, adding columns to the dataframe always give me error. For example:

dt <- data.frame()
for (a in  0:2) {
    table <- tryCatch(
                { mtcars %>%
                    filter(am==a) %>% 
                    group_by(vs) %>% 
                    summarise(n=n()) %>% 
                    spread(vs, n)
                },
                error = function(e) {
                    return(NULL)
                } )

    table$am = a 
    dt <- bind_rows(dt, table)
}

Here is the error message:

 Error in `$<-.data.frame`(`*tmp*`, "am", value = 2L) : replacement has 1 row, data has 0

Anyone can help solving this issue? Thanks a lot.

Upvotes: 0

Views: 352

Answers (3)

MKR
MKR

Reputation: 20095

One option could be to declare your data.frame with valid columns but 0 rows. This provides flexibility to add row using nrow(data)+1 and assigned values of desired columns.

data = data.frame(ID = integer(), Result = integer())

data[nrow(data)+1,] = c(1, 5)
data
# ID Result
# 1  1      5

EDIT

OP is facing problem with the tryCatch block. It seems there are conditions when exception is thrown from tryCatch block and value of table is assigned as NULL in such cases.

The possible fix can be to replace

table$am = a 
dt <- bind_rows(dt, table)

lines with

  if(!is.null(table)){
    table$am = a 
    dt <- bind_rows(dt, table)
  }else{
    dt[nrow(dt)+1, "am"] <- a
  }

Upvotes: 1

bala83
bala83

Reputation: 443

You can't add entries to an empty data.frame like that. Try data = data.frame("ID"=1,"Result"=5)

Upvotes: 0

iod
iod

Reputation: 7592

data<-data.frame(rbind(data, ID=1))

Upvotes: 0

Related Questions