我有一个约60列的数据框,我想做一个主成分分析(PCA),但只包含一些列。有没有办法在唯一标签下重新组合这些列并在反应式输出中调用该标签?
这是一个可重复的示例:
library(easypackages)
libraries("readxl", "tidyselect", "DT", "shiny", "treemap", "plm", "shinydashboard", "data.table", "formattable", "plotly", "FactoMineR", "factoextra")
CAT1 <- mtcars[, 3:5]
CAT2 <- mtcars[, 5:8]
noms1 <- names(CAT1)
noms2 <- names(CAT2)
choices
中:ui <- dashboardPage(
dashboardHeader(title = "test with mtcars", titleWidth = 1000),
dashboardSidebar(
selectizeInput("var.acp", "PCA variables",
choices = c("noms1", "noms2"),
selected = "noms1", multiple = FALSE),
selectizeInput("sample", "Sample", choices = unique(rownames(mtcars)),
selected = rownames(mtcars), multiple = TRUE)
),
dashboardBody(
tabsetPanel(
tabPanel("test with mtcars",
box(title = "PCA mtcars",
status = "primary",
solidHeader = TRUE,
collapsible = TRUE,
dataTableOutput("pca"),
width = 12)
)
)
)
)
server <- function(input, output) {
sample.choice <- reactive({
out <- input$sample
out
})
acp <- reactive({
out <- input$var.acp
out
})
user.selection <- reactive({
data.user <- mtcars[rownames(mtcars) %in% sample.choice(), ]
data.user <- mtcars[, acp()]
})
output$pca <- renderDataTable({
dpca <- user.selection()
dpca <- na.omit(dpca)
tmp <- prcomp(dpca, scale = TRUE)
tmp <- data.table(get_eig(tmp))
tmp
})
}
shinyApp(ui, server)
输出应该是一个表,其中包含在mtcars
的两个子组中的每个子组上实现的PCA的特征值。
但是,出现错误:undefined columns selected
。该错误必定是data.user <- mtcars[, acp()]
引起的,但这很奇怪,因为mtcars
在我调用列时会识别它们:
head(mtcars[, noms1])
# disp hp drat
# Mazda RX4 160 110 3.90
# Mazda RX4 Wag 160 110 3.90
# Datsun 710 108 93 3.85
# Hornet 4 Drive 258 110 3.08
# Hornet Sportabout 360 175 3.15
# Valiant 225 105 2.76
有没有办法解决这个问题? (很抱歉,如果消息有点长)
答案 0 :(得分:0)
根据史蒂芬·洛朗(StéphaneLaurent)的回答,以下是解决方法:
acp <- reactive({
out <- switch(input$var.acp, "noms1"=noms1, "noms2"=noms2)
out
})
代替
acp <- reactive({
out <- input$var.acp
out
})
在server
中。