0

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.

MJP
  • 5,327
  • 6
  • 18
  • 18
  • To what are you adding three or multiplying by 3? Is "vector" a character or a factor vector? – MrFlick Aug 06 '14 at 18:45
  • The elements in the vector only indicate which function should be used. The function operates on different values. Does that help? – MJP Aug 06 '14 at 18:52

2 Answers2

3

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
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
0

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)
nfmcclure
  • 3,011
  • 3
  • 24
  • 40