首页 > 解决方案 > 通过闪亮应用程序中的列名组合子集数据框

问题描述

我有下面的数据框:

DF2 = data.frame(agency_postcode = factor(rep(c(12345,45678,24124,32525,32325),2)),
                 car_group=factor(rep(c("Microcar","City car","Supermini","Compact","SUV"),2)),
                 transmission=factor(rep(c("automatic","manual"),5)))

我有一个闪亮的,用户从中选择一个或多个列名。What I want to achieve is after selecting a column name to have return all the values of the dataframe equal to the first row of this column.The same logic should be applied when more than one columns selected.So for example if I select all three列然后必须返回数据框的第一行而不是无。

#ui.r
library(shiny)
library(DT)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
                 selectInput("sel","Filter by:",
                             choices = colnames(DF2),
                             multiple=T,selected = "agency_postcode")

    ),
    mainPanel(
      DT::dataTableOutput("D")

    )
  )
)
#server.r
#server.r
library(shiny)
library(DT)
server <- function(input, output) {

  output$D<-renderDataTable({
    DE<-DF2[ which(DF2[,input$sel] %in% DF2[1, input$sel]), ]
    datatable(DE)
  })

}

标签: rshiny

解决方案


我们只需要指定行索引、列名(或列索引)并drop处理案例以避免将 data.frame 的维度简化vector为默认情况下的单列、单行案例 ( drop = TRUE) 如果我们检查?Extract

x[i, j, ... , drop = TRUE]

drop - 用于矩阵和数组。如果为 TRUE,则将结果强制转换为可能的最低维度(参见示例)。这仅适用于提取元素,不适用于替换。有关详细信息,请参阅下降。

DE <- DF2[1, input$sel, drop = FALSE]

通过更改,该应用程序可以正常工作

在此处输入图像描述


推荐阅读