在R Shiny中动态添加列名称

时间:2018-08-27 05:26:46

标签: r

在这里对R相当陌生,而不是经验丰富的编码人员。我想创建一个简单的函数,以通过R Shiny上传外部文件,但是该文件将没有固定的列数,并且可能有也可能没有列名。

在原始文件没有标题的情况下,我希望将第一列的名称强制为“ Date”,其余的2,3,4 ...,n列为“ Investment 1” “,”投资2“,”投资3“,...,”投资n-1“

这是我当前的代码,服务器端,

server <- function(input, output) {

rawdata <- reactive({
file_to_read = input$file
if(is.null(file_to_read)) {
  return()
} 
    data <- read.table(file_to_read$datapath, sep = input$sep, header = 
input$dataheader)
})


addcolumn <- reactive({
if(input$dataheader = FALSE) {
paste("Date",colnames(rawdata()[,1]))
  for (i in 2:ncol(rawdata())) {
    paste("Investment " + i, colnames(rawdata()[,i]))
  }
}
})

output$datatable <- renderTable({
If(input$dataheader = FALSE) {
  addcolumn(rawdata())
} else {
rawdata()
}
})

和ui端

dashboardBody(
    tabItems(
      tabItem(
        tabName = "import",
        fluidRow(
          box(
            title = "Instructions",
            solidHeader = TRUE,
            width = 12,
            status = "warning",
            height = 120, 
            textOutput("instructionsImport")
          ),
          box(
            solidHeader = FALSE,
            width = 3,
            status = "primary",
            fileInput("file","Choose a file to upload"),
            radioButtons("sep","Separator",choices = c(Comma = ",", Space = " ",Period = ".", Tilde = "~", minus = "-")),
            checkboxInput("dataheader","File has header?")
          ),
          box(
            title = "Uploaded Data",
            solidHeader = TRUE,
            width = 9,
            status = "primary",
            tableOutput("datatable")
          )
        )
      ),

理想情况下,我希望在导入后执行一次添加列名的操作,并创建结果数据表,而不是为添加列创建响应函数。

谢谢

1 个答案:

答案 0 :(得分:0)

只需将您的server.R代码更改为:

server <- function(input, output) {

  rawdata <- reactive({
    file_to_read = input$file
    if(is.null(file_to_read)) {
      return()
    } 
    data <- read.table(file_to_read$datapath, sep = input$sep, header = 
                         input$dataheader)
    if(!input$dataheader){
      colnames(data)<-c("Date",paste("Investment",1:(ncol(data)-1)))
    }
    return(data)
  })


  output$datatable <- renderTable({
    rawdata()
  })
}