访问闪亮r内部的变量并重新使用它

时间:2019-01-29 19:19:50

标签: r shiny

我在聚类图中定义了一个名为y_kmeans的全局变量,如下所示:我想稍后在表中使用此变量:

Server.R

  output$plot4<-renderPlot({
        df<-rawdata()
        #clustering of Related IP address and the number of movie downloads and number of user_id
        df<- na.omit(df)
        df5 <-df[3:4]
        #%>% dplyr::select(user_id,pa_content_name)
        #set.seed(12)
        split <- sample.split(df5, SplitRatio = 0.85)
        training_set <- subset(df5, split == TRUE)
        test_set <- subset(df5, split == FALSE)
        # Feature Scaling
        training_set = scale(training_set)
        test_set = scale(test_set)
        # Using the elbow method to find the optimal number of clusters
        # Fitting K-Means to the dataset
        set.seed(28)
        kmeans = kmeans(x = df5, centers = 3)
        y_kmeans <<- kmeans$cluster

      })

因此,要在表中添加此变量,我使用了以下代码:

#Demand of titles 
  GroupingVal <- reactive({
    df<-rawdata()
    #Grouping the Values based on clustering
    df$cluster<-kmeans$cluster
    df<-df %>% mutate(group=ifelse(cluster==1,"A",
                                   ifelse(cluster==2,"B",
                                          ifelse(cluster==3,"outlier","outlier"
                                          ))))
    df
  })

和与renderDatatable相关的代码如下:

 output$filteredtbl<-DT::renderDataTable({
    if(is.null(GroupingVal)){return()}
        DT::datatable(GroupingVal(),extensions="Responsive",options=list(pageLength=3),class='cell-border strip',selection='single')
      })

我收到的错误是 “类型为'closure'的对象不可子集化” 您能告诉我问题出在哪里吗?

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式获取它:

Parent

然后在GroupingVal反应函数中调用k_means():

k_means<-reactive({
    #clustering to find the groups of passionate IPS
    df<-rawdata()
    #clustering of Related IP address and the number of movie downloads and number of user_id
    df<- na.omit(df)
    df5 <-df[3:4]
    #%>% dplyr::select(user_id,pa_content_name)
    #set.seed(12)
    split <- sample.split(df5, SplitRatio = 0.85)
    training_set <- subset(df5, split == TRUE)
    test_set <- subset(df5, split == FALSE)
    # Feature Scaling
    training_set = scale(training_set)
    test_set = scale(test_set)
    # Using the elbow method to find the optimal number of clusters
    # Fitting K-Means to the dataset
    set.seed(28)
    kmeans = kmeans(x = df5, centers = 3)
    y_kmeans <<- kmeans$cluster
    y_kmeans
  })

然后在renderDatatable中调用它:

GroupingVal <- reactive({
    df<-rawdata()
    df$cluster<-k_means()
    df<-df %>% mutate(group=ifelse(cluster==1,"A",
                                   ifelse(cluster==2,"B",
                                          ifelse(cluster==3,"outlier","outlier"
                                          ))))
    df
  })