0

I have created a function futureHighs which creates a named list with the average temperature in each scenario. I want to modify the function so that it returns a useful error message if the city is not in the dataset.

futureHighs <- function(ex, city){
  if missing(city=="Ankara"){ stop("Ankara is not in dataset")
    }else
    p <- ex %>% 
      filter(year>=2080&year<=2100) %>%
      filter(scenario=="RCP2.6") %>%
      filter(city=="Ankara")
    HighTemp2.6 = mean(p$txx)
    s <- ex %>%
      filter(year>=2080&year<=2100) %>%
      filter(scenario=="RCP8.5") %>%
      filter(city=="Ankara")
    HighTemp8.5 = mean(s$txx)
    
    list(HighTemp2.6, HighTemp8.5)
  }

I have tried this but it doesn't return an error even if I change the city name to something random. Feel like I'm doing something wrong with the ifelse or the missing function. Any help appreciated. Thanks

Matzo
  • 11
  • Hi Matzo, can you provide a snapshot of your data, i.e. `ex`? Add - for example - `head(ex)` to your question. You will find a lot of friends here, when you make your problem reproducible. Please also check opening and closing brackets, i.e. `if( missing(...) ){ stop(....)}else{ ... }`. P.S. also check if you do not want to use `if(city != "Ankara")`. The function `missing()` checks for the argument ... not the value. – Ray Nov 05 '22 at 20:01
  • Welcome to SO. You've shared some code, which is a good start, but it helps to know what your data look like. Please read these guidelines and edit your question to address the points made in the guidelines. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?r=Saves_AllUserSaves – John Polo Nov 05 '22 at 20:05

1 Answers1

0
if ((mtcars |> filter(cyl == 1) |> dim() |> pluck(1)) == 0) {
  stop("1 is not in dataset")
} else {
  "Your code here"
}

Using mtcars as the dataset, as we don't have your dataset (ex)

Isaiah
  • 2,091
  • 3
  • 19
  • 28