我的数据框:
structure(list(NEWSEC = c("A1", "A1", "A1", "A1", "A2", "A2",
"A2"), tiles = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L), .Label = c("1st",
"2nd", "3rd", "4th"), class = c("ordered", "factor")), AVG = c(360,
594, 868, 1534, 349, 592, 861)), .Names = c("NEWSEC", "tiles",
"AVG"), row.names = c(NA, 7L), class = "data.frame")
看起来像这样:
NEWSEC tiles AVG
1 A1 1st 360
2 A1 2nd 594
3 A1 3rd 868
4 A1 4th 1534
5 A2 1st 349
6 A2 2nd 592
7 A2 3rd 861
当我使用基础R的重塑功能时
reshape(df, idvar = "NEWSEC", timevar = "tiles", direction = "wide")
这非常有效...但我的数据框是通过闪亮的应用程序输入动态生成的,而不是NEWSEC,我可以选择市场或类别。通常我将输入变量分配给一个对象并在我的函数中引用该对象。例如:
sec <- input$colvar
然而,当我尝试使用重塑的类似方法时,它无效。到目前为止我的代码:
reshape(df, idvar = sec, timevar = "tiles", direction = "wide").
我也试过用引号粘贴变量sec但是没有用。
reshape(df, idvar = paste(""",sec,""", sep = "), timevar = "tiles", direction = "wide").
我不知道这是不对的......但是刚试过。
答案 0 :(得分:1)
这部分代码是正确的
sec <- input$colvar
reshape(df, idvar = sec, timevar = "tiles", direction = "wide")
前提是您在被动上下文(reactive
/ render*
函数)中执行此操作,并且df
已经有这两个新列。
但是,您将这两个变量动态添加到数据框df
,因此您必须在某个reactive
/ eventReactive
函数中执行此操作,例如:
data <- reactive({
# let's pretend that this only happens when some conditions are met
new <- df
new$Market <- gl(n = 2, k = 4, length = 7, labels = c("Market1", "Market2"))
new$Category <- gl(n = 2, k = 4, length = 7, labels = c("Cat1", "Cat2"))
new
})
说,现在您想根据所选的id变量重新整形这个新的动态数据帧,然后将其渲染为表格。为此,您必须使用renderTable
功能并通过data()
访问新数据框。
output$new <- renderTable({
# access dynamic data frame "data" via "data()"
sec <- input$colvar
reshape(data(), idvar = sec, timevar = "tiles", direction = "wide")
})
完整示例:
library(shiny)
df <- structure(list(NEWSEC = c("A1", "A1", "A1", "A1", "A2", "A2",
"A2"), tiles = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L),
.Label = c("1st", "2nd", "3rd", "4th"),
class = c("ordered", "factor")),
AVG = c(360,594, 868, 1534, 349, 592, 861)),
.Names = c("NEWSEC", "tiles", "AVG"),
row.names = c(NA, 7L), class = "data.frame")
ui <- fluidPage(
fluidRow(
column(4,
selectInput("colvar", "Variable:",
choices = c("NEWSEC", "Market", "Category"))
),
column(8,
h4("old"), tableOutput("old")
),
h4("new"), tableOutput("new"))
)
server <- function(input, output) {
# dynamic data frame
data <- reactive({
new <- df
new$Market <- gl(n = 2, k = 4, length = 7, labels = c("Market1", "Market2"))
new$Category <- gl(n = 2, k = 4, length = 7, labels = c("Cat1", "Cat2"))
new
})
output$old <- renderTable({
# access dynamic data frame "data" via "data()"
data()
})
output$new <- renderTable({
# access dynamic data frame "data" via "data()"
sec <- input$colvar
reshape(data(), idvar = sec, timevar = "tiles", direction = "wide")
})
}
shinyApp(ui = ui, server = server)