R语言 在shiny应用程序中通过fileInput()上传相同csv后,NA值显示为空白

brgchamk  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(157)

在下面的shiny应用程序中,我首先用read_csv导入到rstudio后显示数据,然后用read.csv()将数据上传到shiny应用程序。第一种情况是正确的,在第二个空单元格中给了我NAs。为什么会发生这种情况

## 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)

xqk2d5yq

xqk2d5yq1#

read_csv()read.csv()在检测NA字符串方面没有相同的默认行为。
默认情况下,read.csv()不会将空字符串转换为NA:

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

read_csv()则:

> 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

您必须提供na.strings参数来更改行为:

> 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

相关问题