Невозможно добавить членство в кластере из kmeans к необработанным данным в Shiny
Я пытаюсь выполнить небольшое блестящее упражнение Kmeans, где я загружаю CSV-файл и запускаю на нем kmeans (игнорируя все необходимые этапы предварительной обработки). После получения кластера я хочу добавить эти номера кластеров к исходным данным и вывести это в интерактивных данных (из пакета DT)...... Но я сталкиваюсь с ошибкой.... код ниже....
library(shiny)
# Loading the required packages
pacman::p_load(Amelia,broom,caret,cluster,clustertend,clValid,corrplot,dbscan,dplyr,DT,data.table,forecast,fpc,FPDclustering,fpp,GGally,ggfortify,ggraph,ggplot2,ggrepel,ggthemes,gmodels,googleVis,gridExtra,igraph,knitr,mice,missForest,NbClust,optCluster,pacman,plyr,purrr,qcc,randomForest,rCharts,reshape2,tibble,tidyr,tidyverse,TSA,tseries,vegan,VIM,zoo) # add 'caret',`IIPR`,'ggthemes','ggraph',igraph,VIM,missForest to the list when using the script in spark envir
#compareGroups
library(markdown)
library(imputeTS)
# Define UI for application
ui <- navbarPage(
# Application title
titlePanel("ShinyApp "),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Select a file ----
fileInput("dataset", "Choose CSV File",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
# Include clarifying text ----
helpText("Note: First select the dataset of csv format only for the App to give any insight!!"),
# Horizontal line ----
tags$hr(),
# Input: Checkbox if file has header ----
checkboxInput("header", "Header", TRUE),
# Input: Select separator ----
radioButtons("sep", "Separator",
choices = c(Comma = ",",
Semicolon = ";",
Tab = "\t"),
selected = ","),
# Horizontal line ----
tags$hr(),
# Input: actionButton() to defer the rendering of output ----
# until the user explicitly clicks the button (rather than
# doing it immediately when inputs change). This is useful if
# the computations required to render output are inordinately
# time-consuming.
actionButton("update", "Update button", class = "btn-primary"),
tags$hr()
),
mainPanel(
tabsetPanel(
navbarMenu("Kmeans",
tabPanel("Raw data with cluster membership",
# Output: Interactive DT table ----
h4("Cluster Table"),
DT::dataTableOutput("cluster_table")
)
),
tabPanel("Random Forest", "This panel is intentionally left blank")
)
)
)
)
# Define server logic
server <- function(input, output) {
datasetInput <- eventReactive(input$update, {
read.csv(input$dataset$datapath,
header = input$header,
sep = input$sep)
}, ignoreNULL = FALSE)
#Selecting only numeric variables
MS.num<- reactive({sapply(datasetInput(), is.numeric)})
MS.DATA.IN.NUM <- reactive({datasetInput()[ , MS.num()]})
# imputing NAs by zeros
df<- reactive({imputeTS::na.replace(MS.DATA.IN.NUM(), 0)})
# Keeping a sample of 10k for modeling
sample_data <-reactive({df()[1:10000,]})
#### Kmeans
opt.cluster=9
set.seed(115)
MS.DATA.KMEANS.Mdl <- reactive({kmeans(scale(sample_data()),opt.cluster,nstart=25)})
# appending clusters to the raw sample data
MS.DATA_KMEANS<-reactive({
x<-MS.DATA.KMEANS.Mdl()$cluster
sample_data()$cluster.kmeans <-x
})
output$cluster_table <- renderDataTable({
DT::datatable(MS.DATA_KMEANS())
})
}
# Run the application
shinyApp(ui = ui, server = server)
Я получаю следующую ошибку:
Error in <-: invalid (NULL) left side of assignment
Stack trace (innermost first):
96: <reactive:MS.DATA_KMEANS> [C:\Users\ADMIN\Documents\shiny_test/app.R#124]
85: MS.DATA_KMEANS
84: base::rownames
83: DT::datatable
82: exprFunc [C:\Users\ADMIN\Documents\shiny_test/app.R#128]
81: widgetFunc
80: func
79: origRenderFunc
78: renderFunc
77: origRenderFunc
76: output$cluster_table
1: runApp
Не знаете, что я делаю не так?
1 ответ
Решение
Нашел решение...
добавление кластеров к необработанным образцам данных
x<-reactive({
cluster<-MS.DATA.KMEANS.Mdl()$cluster
cluster
})
output$x1 <- renderPrint({
dataset <- x()
table(dataset)
})
add_to_df <- reactive({
sample_data1<-cbind(sample_data(),x())
sample_data1
})
output$cluster_table <- renderDataTable({
DT::datatable(add_to_df())
})
Просто нужно было использовать cbind() здесь....