How can I choose a function, depending on the element in a vector?
E.g. vector (a,b,a,b,b)
element a => x + 2
element b => y * 3
I am thinking about a switch statement, but don't know whether this is good R style or not.
How can I choose a function, depending on the element in a vector?
E.g. vector (a,b,a,b,b)
element a => x + 2
element b => y * 3
I am thinking about a switch statement, but don't know whether this is good R style or not.
If you want to do it using switch
, this would probably the way
Define the switch
function
Myswitch <- function(x, type) {
switch(type,
"a" = x + 2,
"b" = x * 3)
}
Create some data
set.seed(123)
x <- sample(10, 5)
x
## [1] 3 8 4 7 6
Your switch vector
vec <- c("a","b","a","b","b")
Vectorized implementation of the function using sapply
sapply(vec, function(y) Myswitch(x, y))
# a b a b b
# [1,] 5 9 5 9 9
# [2,] 10 24 10 24 24
# [3,] 6 12 6 12 12
# [4,] 9 21 9 21 21
# [5,] 8 18 8 18 18
If you want to use it per entry (instead of for the whole x
at a time), use mapply
instead
mapply(Myswitch, x, vec)
## [1] 5 24 6 21 18
I don't know how to add or multiply a character element, but maybe this will get you started.
set.seed(42)
vec1 = c('a','b','a','b','b')
vec2 = runif(length(vec1))
vec3 = sapply(1:length(vec1), function(x){
if (vec1[x] == 'a'){
vec2[x] + 3
}else{
vec2[x] * 3
}
})
Edit: Even quicker way:
vec3 = ifelse(vec1=='a',vec2 + 3, vec2 * 3)