rif-statementmailmergeflextable

I am getting the error "Error in if (first) { : the condition has length > 1" when my condition is a length of 1 in R


For this task I need to add rows to a flextable object if a single observation in my first row is a certain string. If the string is "blue" I need to add data from one data set. If it's "brown" I need to add from a different data set. Most of the time I don't need to append these rows, but there are some cases I do. I end up needing this function to produce ten tables throughout a document running my_function(ARG = 1) through my_function(ARG = 10). Is there a better way to do this?

my_condition = starwars[1,6]
length(starwars[1,6])
my_condition %in% c("blue","brown")

my_function = function(ARG){
  
  ft = flextable(starwars %>% filter(height>ARG*60))
  
  if(my_condition %in% c("blue","brown")){
    # nested if statement
    if(my_condition == "blue"){ # assigning which table to pull data from based off of eye color
      ft = flextable::add_body_row(ft,list(mtcars[ARG,2],"",""))
    }else{
      ft = flextable::add_body_row(ft,list(cars[ARG,2],"",""))
    }
    ft = ft %>% 
      bold(i = 1) %>%
      italic(i = 1) %>%
      fontsize(i = 1, size = 16)
  }
}

my_function(ARG = 3)

I got the following error: Error in if (first) { : the condition has length > 1 Called from: add_rows.fpstruct(x[[i]], nrows, first = first)


Solution

  • You have to explicitly add values in your flextable::add_body_row() function:

    library(dplyr)
    library(flextable)
    
    my_condition = starwars[1,6]
    length(starwars[1,6])
    my_condition %in% c("blue","brown")
    
    my_function = function(ARG){
      
     
      
      ft = flextable(starwars %>% filter(height>ARG*60))
      
      if(my_condition %in% c("blue","brown")){
        # nested if statement
        if(my_condition == "blue"){ # assigning which table to pull data from based off of eye color
          ft = flextable::add_body_row(ft, values = list(mtcars[ARG,2],"",""))
        }else{
          ft = flextable::add_body_row(ft, values = list(cars[ARG,2],"",""))
        }
        ft = ft %>% 
          bold(i = 1) %>%
          italic(i = 1) %>%
          fontsize(i = 1, size = 16)
      }
    }
    
    my_function(ARG = 3)