I think my question is best asked by showing an example.
This simple functions works well with a singular input, but also works fine when given a vector, it simply returns a vector of answers.
simplefun <- function(x,y) {
n <- x+y
return(n)
}
Single input for x:
> simplefun(2,3)
[1] 5
Vector input for x:
> simplex <- 1:10
> simplefun(simplex,3)
[1] 4 5 6 7 8 9 10 11 12 13
So far so good.
Here is a dataframe and function that works fine with a single input, but fails with an input vector:
df <- tibble(name = c("bob", "bob", "iga", "iga", "gilbert" ,"gilbert"),
result = c(1,2,1,2,1,2),
val = c(3,5,6,7,8,9))
lookup <- function(n, r) {
v <- df %>%
filter(name == n) %>%
filter(result == r) %>%
pull(val)
return(v)
}
Single input:
> lookup("bob", 2)
[1] 5
Vector input:
> lookup(names, 2)
[1] 7
I expected to see an output of [1] 5 7
, but that's not what happens.
In my mind I thought R basically treated inputs like this with something like a for loop: feeding element 1 into the function, then element 2, and so on. Playing around with this, I gather that's not what's happening.
I was actually able to get my actual function to work with lapply/sapply, but it was very slow.
So my question is: What's the best / correct way to write the function like the lookup function above so it can take a vector as an input (and therefore be used in a mutate() function operating on a dataframe)?
What is R actually doing in my two above functions that results in one returning a vector and the other not?
Thanks very much,
Luke