rpowerpointflextableofficer

Powerpoint distorting flextable when using {officer}


When I run the code to produce the flextable within R it looks exactly as I want, but when I use the {officer} package to put it into a powerpoint slide it stretched the height, adding extra space between the lines. I think this is because of the NAs, but how do I correct it? This df works:

df1 <-as.data.frame(matrix(sample(1:8, 6*8, replace = TRUE), nrow = 8, ncol = 6))
df1 |> flextable(cwidth = 0.4, cheight = 0.1) |> fontsize(size = 8) |> width(j = 1, width = 0.5) |> padding(padding = 0) |> height_all(height = 0.2, unit = "cm") |> hrule(rule = "exact")

but this doesn't

df2 <- data.frame(
  Column1 = LETTERS[1:6],  # Letters in the first column
  Column2 = sample(c(0:9, rep(NA, 2))),  # 1-digit random numbers and blanks
  Column3 = sample(c(0:9, rep(NA, 2))),
  Column4 = sample(c(0:9, rep(NA, 2))),
  Column5 = sample(c(0:9, rep(NA, 2))),
  Column6 = sample(c(0:9, rep(NA, 2))),
  Column7 = sample(c(0:9, rep(NA, 2))),
  Column8 = sample(c(0:9, rep(NA, 2)))
)
df2 |> flextable(cwidth = 0.4, cheight = 0.1) |> fontsize(size = 8) |> width(j = 1, width = 0.5) |> padding(padding = 0) |> height_all(height = 0.2, unit = "cm") |> hrule(rule = "exact")

flextable seems to be handling NAs differently than numbers or characters


Solution

  • The problem is that font sizes are not applied to cells with empty strings (this also happens if you replace NA with ""). This issue is currently listed here: https://github.com/davidgohel/flextable/issues/153

    The best workaround at the moment would be to replace all NAs with a whitespace.

    df2 <- data.frame(
      Column1 = c(LETTERS[1:5], ""), # adding an empty string for good measure
      Column2 = sample(c(0:9, rep(NA, 2))),
      Column3 = sample(c(0:9, rep(NA, 2))),
      Column4 = sample(c(0:9, rep(NA, 2))),
      Column5 = sample(c(0:9, rep(NA, 2))),
      Column6 = sample(c(0:9, rep(NA, 2))),
      Column7 = sample(c(0:9, rep(NA, 2))),
      Column8 = sample(c(0:9, rep(NA, 2)))
    )
    
    # replace NAs and empty strings with whitespace
    df2[(is.na(df2) | df2 == "")] <- " "
    # alternatively, you can also set flextable defaults
    # set_flextable_defaults(na_str = " ")
    
    
    df2_flextable <- (
      df2
      |> flextable(cwidth = 0.4, cheight = 0.1)
      |> fontsize(size = 8)
      |> width(j = 1, width = 0.5)
      |> padding(padding = 0)
      |> height_all(height = 0.2, unit = "cm")
      |> hrule(rule = "exact")
    )
    
    my_pres <- read_pptx()
    my_pres <- add_slide(my_pres, layout = "Title and Content", master = "Office Theme")
    
    my_pres <- ph_with(my_pres, df2_flextable, ph_location_type(type = 'body'))
    print(my_pres, target = 'presentation.pptx')