jeudi 2 avril 2020

Using %>% and ifelse() inside a function

I would like to run a function to test if a value exists in a dataset or not. I've looked for answers and since found a workaround but it's not as neat and I'm curious why my initial attempt failed.

Here's a simplified dataset

df <- structure(list(country = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("IRE","USA"), 
class = "factor"), year = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("1990", "1995", "2000"),
class = "factor")), class = "data.frame", row.names = c(NA, -6L))

> df
  country year
1     IRE 1990
2     IRE 1995
3     IRE 2000
4     USA 1990
5     USA 1995
6     USA 2000

I would like my function to return a 1 if a particular country code and year are present or a 0 otherwise. This is the working code:

myFunc <- function(x,y){
  p.ans <- df %>% filter(year == y) 
  ifelse(x %in% p.ans$country, 1, 0)
}

> myFunc("USA", 1995)
[1] 1

> myFunc("USA", 1997)
[1] 0

But why doesn't this alternative code work? Is there a variation of it that would?

myFunc <- function(x,y){
  df %>% filter(year == y) %>% ifelse(x %in% country, 1, 0)
}

> myFunc("USA", 1997)
 Error in ifelse(., x %in% country, 1, 0) : unused argument (0)

Thanks!

Aucun commentaire:

Enregistrer un commentaire