Home > other >  NA value is displayed as blank after uploading the same csv via fileInput() in shiny app
NA value is displayed as blank after uploading the same csv via fileInput() in shiny app

Time:12-16

In the shiny app below first I display data after importing to rstudio with read_csv and then after uploading it to shiny app with read.csv(). The fist case which is corect gives me NAs w3hile the second empty cell. Why does this happen

## app.R ##
library(shiny)
library(shinydashboard)
library(readr)
#eventex <- read_csv("eventlog_new_format3011.csv")
eventex<-structure(list(case_id = "0003397585", action = "0003397585-B52-R", 
                        resource = "B52-R", activity = NA_character_, registration_type = "Stopp", 
                        timestamp = structure(NA_real_, tzone = "", class = c("POSIXct", 
                                                                              "POSIXt")), `Prod antall` = 3743, product_type_text = "Skyr Luftig tropisk 130gx8", 
                        Ordrenummer = "0003397585", lifecycle = NA, `Sum of TotalQty` = 3743, 
                        Produkt = "K101322", PurchaseItem = NA_character_, Innsatsfaktor = "K101171", 
                        Artikkeltype = "FP", `Alt. Work Center` = NA_character_), row.names = c(NA, 
                                                                                                -1L), class = c("tbl_df", "tbl", "data.frame"))
ui <- dashboardPage(
  dashboardHeader(

  ),
  dashboardSidebar(
    fileInput("file1", "",
              accept = c(
                "text/csv",
                "text/comma-separated-values,text/plain",
                ".csv")),
    radioButtons("separator","Separator: ",choices = c(";",","), selected=",",inline=TRUE)
  ),
  dashboardBody(
               verbatimTextOutput("pr"),
               verbatimTextOutput("pr2")),
  
)

server <- function(input, output,session) {
  
    View(eventex[74,4])
    
    dataset<-reactive({
      inFile <- input$file1
      
      if (is.null(inFile))
        return(NULL)
      
      p1<-read.csv(inFile$datapath, header = T,sep = ",")
      

    })
output$pr<-renderPrint(
  eventex[74,4]
)
output$pr2<-renderPrint(
  dataset()[74,4]
)
}


shinyApp(ui, server)

enter image description here

CodePudding user response:

read_csv() and read.csv() don't have same default behavior for detecting NA strings.

read.csv() doesn't convert empty strings to NA by default:

> read.csv(text = "a, b\nA, 0\n,NA\nNA,2")
     a  b
1    A  0
2      NA
3 <NA>  2

while read_csv() does:

> read_csv("a, b\nA, 0\n,NA\nNA,2")
# A tibble: 3 x 2
  a         b
  <chr> <dbl>
1 A         0
2 NA       NA
3 NA        2

You have to supply na.strings parameter to change the behavior:

> read.csv(text = "a, b\nA, 0\n,NA\nNA,2", na.strings = c("", "NA"))
     a  b
1    A  0
2 <NA> NA
3 <NA>  2
  • Related