rshinyreactivefactoring

R Shiny - How to factor inside a reactive function?


I'm trying to factor this data so that my ggplot has the axes and colors aligned to the correct cell types and I need to factor at some point to do so. However, shiny gives me this error:

Error:`data` must be a [34m<data.frame>[39m, or an object coercible by `fortify()`, not a <factor> object.

I know it can't be a factor object, but I'm not sure how else to factor it. Any help would be much appreciated!

filtData <- reactive({  
        
    #this is working
    data <- filter(data, gene == gene())
    
    #this is not working
    data$celltype <- factor(data$celltype, levels <- c("Granulocytes", "Monocytes", 
                                                       "T-cells", "B-cells", "Dendritic cells",
                                                       "NK-cells", "Total PBMC"))

I tried this, but to no avail:

data$celltype <- lapply(data$celltype, levels <- c("Granulocytes", "Monocytes", 
                                                   "T-cells", "B-cells", "Dendritic cells",
                                                   "NK-cells", "Total PBMC"), as.factor)

Solution

  • Does this work using dplyr?

    filtData <- reactive({  
      
      
      data <- data %>%
        filter(gene == gene()) %>%
        mutate(celltype = factor(celltype, levels <- c("Granulocytes", "Monocytes", 
                                                         "T-cells", "B-cells", "Dendritic cells",
                                                         "NK-cells", "Total PBMC"))
        )
    })