Reputation: 58
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!
Upvotes: 3
Views: 56
Reputation: 545528
But why doesn't this alternative code work?
Because x %>% f(y)
is the same as f(x, y)
. Thus the code you wrote is equal to
ifelse(filter(df, year == y), x %in% country, 1, 0)
… which is not how the ifelse
function works.
Instead, you could write
df %>% filter(year == y) %>% pull(country) %>% {ifelse(x %in% ., 1, 0)}
Here you need to surround the ifelse
function call with {…}
to prevent the pipe from inserting the right-hand side as the first argument into the function call (we want to use x %in% .
as the first argument rather than just .
).
… or, if you’ve loaded the ‘magrittr’ package, you can use %$%
instead of %>% pull(…) %>% {…}
:
df %>% filter(year == y) %$% ifelse(x %in% country, 1, 0)
Upvotes: 5