创建包含2个随机样本的新变量

时间:2017-10-03 04:02:29

标签: r ggplot2 rstudio shiny

我的目标是让一个图有2个柱:1个用于过滤的数据集,1个用于未过滤的数据集。当我输出我的情节时,我有一个宽条。我相信我需要将mysample和mysample2组合成一个新变量并在x轴上绘制。如果有人有不同的想法,请随时让我知道,我真的坚持如何完成这项工作。enter image description here

另外,我知道x =输入$ obs是完全错误的,但我不知道还有什么可以尝试。

filtered = readxl::read_excel("/Filter.xlsx")
unfiltered = readxl::read_excel("/Unfilter.xlsx")

UI:

ui = fluidPage(
  sliderInput("obs", "Number of Observations", value = 550, min = 100, max = 1000),
  plotOutput("filter")
)  

服务器:

server = function(input, output) {
  output$filter = renderPlot({
    mysample = filtered[sample(1:nrow(filtered), input$obs,
                            replace=FALSE),]
     mysample2 = unfiltered[sample(1:nrow(unfiltered), input$obs,
                            replace=FALSE),]


  ggplot(NULL, aes_string(x = input$obs)) +
    geom_col(data = mysample, aes(y = Net_Return)) +
    geom_col(data = mysample2, aes(y = Net_Return)) +

    labs(y = "Net Return") +
    theme_bw() +
    scale_y_continuous(labels = scales::dollar)     
 })
}  

1 个答案:

答案 0 :(得分:2)

我认为你是对的;您需要一个包含已过滤和未过滤数据的数据框。我认为您服务器功能的代码可以使用,但我不确定您使用aes_string()的原因,...

server = function(input, output) {
  output$filter = renderPlot({
    mysample = filtered[sample(1:nrow(filtered), input$obs,
                            replace=FALSE),]
     mysample2 = unfiltered[sample(1:nrow(unfiltered), input$obs,
                            replace=FALSE),]
    tbl = bind_rows(filtered = mysample, unfiltered = mysample2,
     .id="type")


  ggplot(tbl, aes(x = type)) +
    geom_col(aes(y = `Net Return`)) +
    labs(y = "Net Return") +
    theme_bw() +
    scale_y_continuous(labels = scales::dollar)     
 })
}