Search code examples
rshinyflexdashboard

Change column name of a reactive data frame in shiny R


I have a code that looks something like this:

d_frame<-reactive(unique(as.data.frame(do.call("rbind", sapply(1:(length(intarr())), 
FUN = function(i) c(substr(readlinesop()
[intarr()[i]+1],17,26),substr(readlinesop()[intarr()[i]+2],17,26)), simplify = FALSE)))))

bv<-reactive(ncol(d_frame()))
colnames(d_frame) <- c("Sand", "Water")
subset_dataset <-eventReactive(input$go, {d<-bv()})

The first line which has the output d_frame creates a data frame. When I try to change the column name of this it throws an error :

enter image description here

So, I tried to find the number of columns in the d_frame using ncol as mentioned above which returned 2. But, I don't know what's causing the error. Can you please help me with this?


Solution

  • Try something like this. Note that the d_frame() is a reactive function. In your calculations you will use d_frame2()

     d <- NULL
     d_frame <-
       reactive(unique(as.data.frame(do.call(
         "rbind", sapply(
           1:(length(intarr())),
           FUN = function(i)
             c(substr(readlinesop()
                      [intarr()[i] +
                          1], 17, 26), substr(readlinesop()[intarr()[i] + 2], 17, 26)),
           simplify = FALSE
         )
       ))))
    
     bv <- reactive(ncol(d_frame()))
     d_frame2 <- reactive({
       testdata <- d_frame()
       colnames(testdata) <- c("Sand", "Water")
       testdata
     })
    
     subset_dataset <- eventReactive(input$go, {
       d <<- bv()
     })