从用户输入 R Shiny 创建分组饼图
Create grouped pie chart from user input R Shiny
我希望用户能够上传 .csv 文件并能够为其创建饼图。如果有一列包含他们想要分组在一起的类别,他们应该能够。
下面的代码显示了我想要做什么,但只有在我编写程序时知道列名(在本例中为性别)时才有效。
piePlotData = aggregate(. ~ Gender, inFile, sum)
pie(piePlotData[[input$pieData]], labels = piePlotData[[input$pieGroups]])
如果可能的话,我想用 input$pieGroups
替换性别
这是一个可以上传的简单数据示例:
Gender Name Maths English
M Bob 4 2
M Fred 1 7
F Mary 5 4
如果之前有人回答过这个问题,我深表歉意,我已经尝试过其他人的解决方案,但是当上传的数据可以是任何格式并且仍然保持相同的列名时,我无法让他们工作。
如果解决方案只使用基本 R 包,我会更喜欢,但任何解决方案都比 none 好:P
提前致谢
(有点)简单的代码示例:
server.R:
library(shiny)
shinyServer(function(input, output, session) {
inFile = reactive({ return (read.csv(file.choose(), header = TRUE))})
observe({
updateSelectInput(session, "pieData", choices = names(inFile()))
updateSelectInput(session, "pieGroups", choices = names(inFile()))
})
output$plot = renderPlot({
piePlotData = aggregate(. ~ Gender, inFile, sum)
pie(piePlotData[[input$pieData]], labels = piePlotData[[input$pieGroups]])
})
})
ui.R:
shinyUI(pageWithSidebar(
headerPanel("Grouped Pie Chart"),
sidebarPanel(
selectInput("pieData", "Columns in pie", "Update"),
selectInput("pieGroups", "Groups for pie", "Update")
),
mainPanel(
plotOutput("plot")
)
))
您可以使用 formula
从字符串创建公式。
例如,在您的 server.R
中,您可以这样做:
piePlotData = aggregate(formula(paste0(".~",input$pieGroups)), inFile(), sum)
我希望用户能够上传 .csv 文件并能够为其创建饼图。如果有一列包含他们想要分组在一起的类别,他们应该能够。 下面的代码显示了我想要做什么,但只有在我编写程序时知道列名(在本例中为性别)时才有效。
piePlotData = aggregate(. ~ Gender, inFile, sum)
pie(piePlotData[[input$pieData]], labels = piePlotData[[input$pieGroups]])
如果可能的话,我想用 input$pieGroups
这是一个可以上传的简单数据示例:
Gender Name Maths English
M Bob 4 2
M Fred 1 7
F Mary 5 4
如果之前有人回答过这个问题,我深表歉意,我已经尝试过其他人的解决方案,但是当上传的数据可以是任何格式并且仍然保持相同的列名时,我无法让他们工作。
如果解决方案只使用基本 R 包,我会更喜欢,但任何解决方案都比 none 好:P 提前致谢
(有点)简单的代码示例:
server.R:
library(shiny)
shinyServer(function(input, output, session) {
inFile = reactive({ return (read.csv(file.choose(), header = TRUE))})
observe({
updateSelectInput(session, "pieData", choices = names(inFile()))
updateSelectInput(session, "pieGroups", choices = names(inFile()))
})
output$plot = renderPlot({
piePlotData = aggregate(. ~ Gender, inFile, sum)
pie(piePlotData[[input$pieData]], labels = piePlotData[[input$pieGroups]])
})
})
ui.R:
shinyUI(pageWithSidebar(
headerPanel("Grouped Pie Chart"),
sidebarPanel(
selectInput("pieData", "Columns in pie", "Update"),
selectInput("pieGroups", "Groups for pie", "Update")
),
mainPanel(
plotOutput("plot")
)
))
您可以使用 formula
从字符串创建公式。
例如,在您的 server.R
中,您可以这样做:
piePlotData = aggregate(formula(paste0(".~",input$pieGroups)), inFile(), sum)