计算闪亮r中输入数据列中唯一向量的数量

时间:2020-08-30 06:34:43

标签: r shiny

我正在尝试使用我的数据找出所选输入中唯一向量的数量。
但是,变量的length(unique(x))的所有结果都是1
您能帮我解决这个问题吗?

这是我的代码。

library(shiny)

ui <- fluidPage(
  fluidRow(
    box(width = 6, height=200, title ="File select", 
        fileInput("file","select file", buttonLabel = "file", accept = c(".csv")),
        DTOutput('dt')),
  selectInput("sel","select",colnames(file)),
  verbatimTextOutput("results")
)
)

server <- function(input, output, session) {
  
  data <- reactive({
    data.table::fread(input$file$datapath)
  })
  
  observeEvent(input$file, {
    mytable <- read.csv(input$file$datapath) %>% as_tibble()
    req(mytable)
    updateSelectInput(session, "sel", label = "select", choices = colnames(mytable))
  })
  
  output$results <- renderPrint({
    length(unique(data()[,input$sel]))
  })
  
}

shinyApp(ui, server)

###################解决方案#####################

server <- function(input, output, session) {
  
  appdata <- reactive({
    read.csv(input$file$datapath)
  })
  
  observeEvent(input$file, {
    mydf <- read.csv(input$file$datapath)
    updateSelectInput(session, "sel", label = "select", choices = colnames(mydf))
  })
  
  output$results <- renderPrint({
    cat(input$sel, '\n')
    length(unique(appdata()[[input$sel]]))
  })
  
}

它确实对我有用!

1 个答案:

答案 0 :(得分:0)

fread返回的数据对象是data.table:

library(data.table)
data <- function(){ as.data.table(mtcars)}
length(unique(data()[,1]))
#> [1] 1

nrow(unique(data()[,1]))
#> [1] 25

reprex package(v0.3.0)于2020-08-30创建

这样做的原因是,对于data.frame / data.table,data [,1]返回另一个data.frame / data.table(具有1列的列表的列表)。
length给出了列数,nrow是您要查找的内容。

相关问题