Home > front end >  filter data in R shiny using predefined variables where some of them could be empty or NA?
filter data in R shiny using predefined variables where some of them could be empty or NA?

Time:07-06

i am trying to build an application with R shiny where i can load that famous data "mpg" and then filter it using a loaded data which is in fact a loaded excel having as column names some of the column names of the mpg data .One of this excel files looks like this:manufacturer, model, displ, year as column names and as values for these columns we have the following:audi,"", 1.8, 1999.the second column has empty value or NA .The code below show how to load that excel files and used to filter the data and then plot something.It is meant by that emtpy value is to choose everythig in the mpg data ,in other words not to filter anything residing in the "model" column:

  newdata<-list()
      
   newdata<-readxl::read_excel(paste0(getwd(),"/","myfolder","/","setting.xlsx"))
       
      dat<- mpg 
      dt<-dat[dat$manufacturer==newdata$manufacturer & dat$model==newdata$model& dat$displ=newdata$displ& dat$year==newdata$year,]

ggplot(dt,aes(displ,cty)) 
geom_point(size=7,colour="#007A9D",shape=4)
      
 

CodePudding user response:

If you only need to check for "equal to" i.e == and your newdata only has one value pr column then a for loop will work.

df <- mpg

# I do not have access to your data, 
# but the functionality is the same with a list
newdata <- list( 
  manufacturer = "audi",
  model = "a4 quattro",
  displ = NA
)

for(f in names(newdata)){
  if(!is.na(newdata[[f]]))
    df <- df[df[[f]] == newdata[[f]],]
}

For each name in the newdata data.frame, the loop chunk is run with f as the name. The df[df[[f]] == newdata[[f]],] then compares each column, but only if newdata[[f]] is not NA.

Of course, a problem will arise if your newdata has columns that are not in the mpg data. Here an additional condition can be made such as if(!is.na(newdata[[f]]) & f %in% df)

  • Related