printing blanks instead of NA's when using formattable in R

前端 未结 2 771
走了就别回头了
走了就别回头了 2021-02-14 18:44

Consider the example data.frame

df <- data.frame(
  id = 1:4,
  name = c(\"Bob\", \"Ashley\", \"James\", \"David\"), 
  age = c(48, NA, 40, 28),
  test1_score         


        
相关标签:
2条回答
  • Another solution which worked for me was using str_remove_all(). Because color_bar() in formattable produces HTML output as a character, you can just remove the string "NA".

    Note that this has the potential to mess up the HTML if you happened to have NA anywhere else. Also worth noting is that I wrap a percent function around your_var. This was the best way I could come up with to convert my numeric to percent and apply color_bar(). The code is below:

    df %>%
        # First mutate w/color_bar()
        mutate(your_var= color_bar("green", na.rm=T)(percent(your_var, digits = 1))) %>% 
        # Second mutate
        mutate(your_var = str_remove_all(your_var, "NA"))
    

    Output from First mutate

    <span style="display: inline-block; direction: rtl; border-radius: 4px; padding-right: 2px; background-color: #00a657">NA</span>
    

    Output from Second mutate

    <span style="display: inline-block; direction: rtl; border-radius: 4px; padding-right: 2px; background-color: #00a657"></span>
    

    Also, in case anyone hasn't seen this yet: Awesome tables in HTML - Integration with formattable

    0 讨论(0)
  • 2021-02-14 19:29

    You could use the sprintf function to format the numeric columns as strings with the desired number of decimal places. In the code below, sprintf converts NA to the string "NA", which we then convert to an empty string.

    # Function to convert numeric values to strings with a given number of 
    #  decimal places, and convert NA to empty string
    fnc = function(var, decimal.places) {
      var = sprintf(paste0("%1.",decimal.places,"f"), var)
      var[var=="NA"] = ""
      var
    }
    
    # Select the columns we want to reformat
    vars = c('age', 'test1_score')
    
    # Apply the function to the desired columns with the desired number of decimal places
    df[ , vars] = mapply(fnc, df[ ,vars], 2:3)
    
    formattable(df, list(
      age = color_tile("white", "orange"),
      test1_score = color_bar("pink", 'proportion', 0.2)
    ))
    

    0 讨论(0)
提交回复
热议问题