r - 将数字列转换为字符
问题描述
我配置了一个 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))) +
解决方案
用而不是重写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()
将其转换为字符串。
推荐阅读
- android - Android Jetpack Compose 导航中的依赖性问题
- javascript - 循环时分页问题的 Swiper 自定义功能:true。怎么修?
- python - 无法在 Vs Code 中提供输入
- javascript - 如何在所有浏览器中连接智能合约?
- javascript - 访问从客户端传递的 nodejs 中的值的问题
- python - 用每个级别的唯一元素替换路径列表 (/)
- python - 如何使用 Selenium 通过文本查找元素?
- c++ - 列表/向量迭代器不会更改派生类中的 const 引用属性
- snowflake-cloud-data-platform - 是否可以选择直接将数据移动到雪花而不通过 S3 和其他云存储
- android - 改造 API 调用返回 null