首页 > 解决方案 > 将数字列转换为字符

问题描述

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

它给了我这个: 在此处输入图像描述


我想要这样的东西: 在此处输入图像描述

这是我的代码:

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

标签: rggplot2shiny

解决方案


用而不是重写ggplot命令应该可以解决问题。aesaes_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()将其转换为字符串。


推荐阅读