Search code examples
rdplyrtidyversetibble

add_row coverts factor/numeric columns to char; cannot add ordered factors


I need to use tibble::add_row function to add a single row into an existing tibble.

df = tibble(cola = as.ordered(c(1, 2, 3)), colb = as.factor(c("xx", "xxx", "xxx")))
df2 = df %>% add_row(tibble_row(cola = 1, colb = as.factor("yyy")))

this coverts my column cola into a char variable. If I change the script into:

df %>% add_row(tibble_row(cola = as.ordered(1), colb = as.factor("yyy")))

I get the following error message:

Error: Can't combine ..1$cola <ordered> and ..2$cola <ordered<5b58e>>.

I experimented with other data structures. add_row works well with numeric and char data formats. But, fails with ordered. For the new row, unless the data type is specified (like as.factor), add_row silently coverts all factors to char. The issue has been reported here. But, I cannot find a solution, such as adding an argument like stringsAsFactors = T. making the new row a tibble with tibble_row() or as_tibble_row() followed by dplyr::bind_rows() doesn't help either as it throws the same error on the ordered factors.

My questions.

  1. How can I stop add_row converting all factors to characters, without defining the data structure for each relevant column the new row?
  2. can add_row not deal with ordered factors?

Solution

  • You need to specify the available ordered levels:

    df %>% add_row(tibble_row(cola = ordered(1, levels = 1:3), colb = as.factor("yyy")))
    # A tibble: 4 x 2
      cola  colb 
      <ord> <fct>
    1 1     xx   
    2 2     xxx  
    3 3     xxx  
    4 1     yyy