Shiny Adding Columns to Nested Object Shiny

Hi Friends,
Below is r shiny code where need to add the column to a nested object.
Unable to do so , please review code and suggest correction.

library(shiny)
library(tidyverse)
library(purrr)
library(rlang)

x<- rnorm(150,200,10)
y<- rnorm(150,120,25)
z <- rep(letters[1:2],75)

df1<-data.frame(x,y,z)


ui<-fluidPage(
  selectInput("Sales", "Select either x or y",choices=names(df1),selected="x"),
  selectInput("Forecast","Select X or Y",choices = names(df1),selected="y"),
  selectInput("Group","Select Variables to Group",choices="z",selected="z"),
  tableOutput("table1")
  
)

server<-function(input,output,session) {
  
  nested_obj <-reactive({
    df1 %>%
    group_by(across(all_of(input$Group))) %>%
    nest()
  })
  
  F_MAPE_NEST <- function(f1,df,x,y){
    f1 %>%
      mutate(df=map(df,~mutate(.x , 
                               Error = abs(.data[[x]] - .data[[y]])*100/ pmax(.data[[x]],.data[[y]]))))
  }            
  
  output$table1<-renderTable({
    
      F_MAPE_NEST(nested_obj(),nested_obj()$data,input$Sales,input$Forecast)%>%
      unnest
    })
    
}
shinyApp(ui=ui,server=server)

-------------------------------------------------------------------
R code that works 
library(tidyverse)


x<- rnorm(150,200,10)
y<- rnorm(150,120,25)
z <- rep(letters[1:2],75)


df1<-data.frame(x,y,z,)


f1<-df1 %>%
  group_by(z)%>%
  nest()

f11<-f1 %>% mutate(WtError=map(data,function(df,x,y) abs(df$x-df$y)/pmax(df$x,df$y)))%>% unnest()

I think it should be

F_MAPE_NEST <- function(base,subdf,xname,yname){
  subdf <- ensym(subdf)
  mutate(base,
         Error=map(!!subdf,
                     function(df) abs(df[[xname]]-df[[yname]])/pmax(df[[xname]],df[[yname]])
         ))
  }

and also

should be

output$table1<-renderTable({
    
    F_MAPE_NEST(nested_obj(),data,input$Sales,input$Forecast)%>%
      unnest
  })
1 Like

Hi Sir , Thanks for your help and reply.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.