Home > Blockchain >  print data frame to pdf with NA's showing as blanks
print data frame to pdf with NA's showing as blanks

Time:05-19

I have a dataframe like this:

df <- data.frame(CAR = c(1,1,3,9,1),
                                         AGE=c(5,6,8,NA,NA),
                                         SEX= c(1,2,2,1,2),
                                         BIKE = c(2,0,4,3,NA),
                                         PLANE = c(8,0,6,7,9),
                                       BOAT = c(1,2,NA,NA,NA),
                                       SCOOTER = c(2,3,6,9,0))

and I want to write the data frame to a pdf. However, I want the NA's on the data frame to come up as blanks in the pdf. Is this possible at all. I have included my code below;

library(grid)    
    library(gridExtra)

    maxrow = 35   
        npages = ceiling(nrow(df)/maxrow)      
        pdf("test.pdf", height = 11, width = 8.5)  
        idx = seq(1, maxrow)  
        grid.table(df[idx,],rows = NULL)  
        for(i in 2:npages){
          grid.newpage();
          if(i*maxrow <= nrow(df)){
          idx = seq(1 ((i-1)*maxrow), i * maxrow)
        }
        else{
          idx = seq(1 ((i-1)*maxrow), nrow(df))
        }
        grid.table(df[idx, ],rows = NULL)
        }
        dev.off()
    

CodePudding user response:

Convert all columns to character and replace NA with empty strings:

library(grid)    
library(gridExtra)

df[] <- lapply(df, function(x) {
  x <- as.character(x)
  x[is.na(x)] <- ""
  x
  })

grid.newpage()
grid.table(df, rows = NULL)

enter image description here

CodePudding user response:

This is the dplyr version of Allan Cameron's solution:

 library(grid)    
 library(gridExtra)
 
 library(dplyr)
 df <-  df %>% 
   mutate(across(everything(), ~replace_na(as.character(.), "")))
 
 grid.newpage()
 grid.table(df, rows = NULL)

enter image description here

  •  Tags:  
  • r
  • Related