将数字列转换为字符

时间:2019-07-19 09:39:47

标签: r ggplot2 shiny

我配置了csv导入功能来显示图形。导入后,我选择定义X,Y和Groupby的列。根据我导入的CSV,ID字段可以是数字或字符。使用此功能,当我导入包含字符ID的CSV时显示的图形是正确的,但是当它包含数字ID时导入的图形却不正确。

它给了我这个enter image description here


我想要这样的东西: enter image description here

这是我的代码:

  #-------- REACTIVE DATA --------#
  data <- reactive({
    req(input$csv_chart)
    infile <- input$csv_chart
    if (is.null(infile))
      return(NULL)
    df <- read_csv(infile$datapath)
    updateSelectInput(session, inputId = 'X', label = 'Field X:',
                      choices = names(df), selected = names(df)[1])
    updateSelectInput(session, inputId = 'Y', label = 'Field Y:',
                      choices = names(df), selected = names(df)[2])
    updateSelectInput(session, inputId = 'group', label = 'Group by:',
                      choices = names(df), selected = names(df)[3])
    return(df)
  })


  #-------- PLOT CHART --------#
  output$plot <- renderPlot({
    ggplot(data()) +
      geom_line(mapping = aes_string(x = input$X, y = input$Y, color= input$group)) +
      labs(x = input$X, y = input$Y, title = "Index Values")
  })

我尝试的是在ggplot函数中添加“ as.character”,但它什么都没有改变:

geom_line(mapping = aes_string(x = input$X, y = input$Y, color= as.character(input$group))) +

1 个答案:

答案 0 :(得分:0)

使用ggplot而不是aes重写aes_string命令应该可以解决问题。

ggplot(data()) +
  geom_line(mapping = aes(x = get(input$X), y = get(input$Y), color = as.character(get(input$group))))

原因是:在aes_string中,您呼叫input$group只是一个字符串。 as.character()在这里毫无意义,因为它将变量名的字符串转换为字符串。

但是,使用aes,您可以使用get()访问变量名称后面的实际数据。然后,您可以根据这些数据使用as.character()将其转换为字符串。

相关问题