Use of switch() in R to replace vector values
Here is the correct way to vectorize a function, e.g. switch:
# Data vector:test <- c("He is", "She has", "He has", "She is")# Vectorized SWITCH:foo <- Vectorize(vectorize.args = "a", FUN = function(a) { switch(as.character(a), "He is" = 1, "She is" = 1, "He has" = 2, 2)})# Result:foo(a = test) He is She has He has She is 1 2 2 1
I hope this helps.
You coud try
test_out <- sapply(seq_along(test), function(x) switch(test[x], "He is"=1, "She is"=1, "He has"=2, "She has"=2))
Or equivalently
test_out <- sapply(test, switch, "He is"=1, "She is"=1, "He has"=2, "She has"=2)
The vectorised form of if
is ifelse
:
test <- ifelse(test == "He is", 1, ifelse(test == "She is", 1, ifelse(test == "He has", 2, 2)))
or
test <- ifelse(test %in% c("He is", "She is"), 1, 2)
switch
is basically a way of writing nested if
-else
tests. You should think of if
and switch
as control flow statements, not as data transformation operators. You use them to control the execution of an algorithm, eg to test for convergence or to choose which execution path to take. You wouldn't use them to directly manipulate data in most circumstances.