Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of switch() in R to replace vector values

This should be pretty simple but even after checking all documentation and on-line examples I don't get it.

I'd like to use switch() to replace the values of a character vector.

A fake, extremely simple, reproducible example:

test<-c("He is", "She has", "He has", "She is") 

Let's say I want to assign "1" to sentences including the verb "to be" and "2" to sentences including the verb "to have". The following DOES NOT work:

test<-switch(test,                 "He is"=1,                 "She is"=1,                 "He has"=2,                 "She has"=2) 

Error message:

+ + + + Error in switch(test, `He is` = 1, `She is` = 1, `He has` = 2, `She has` = 2) :    EXPR must be a length 1 vector 

I think EXPR is indeed a length 1 vector, so what's wrong?

I thought maybe R expected characters as replacements, but neither wrapping switch() into an "as.integer" nor the following work:

test<-switch(test,                 "He is"="1",                 "She is"="1",                 "He has"="2",                 "She has"="2") 

Maybe it doesn't vectorize, and I should make a loop? Is that it? Would be disappointing, considering the strength of R is vectorization. Thanks in advance!

like image 217
torwart Avatar asked Jul 01 '15 09:07

torwart


People also ask

How do I replace data in a vector in R?

To replace a value in an R vector, we can use replace function. It is better to save the replacement with a new object, even if you name that new object same as the original, otherwise the replacements will not work with further analysis.

How do you replace all values in a vector?

The replacement of values in a vector with the values in the same vector can be done with the help of replace function. The replace function will use the index of the value that needs to be replaced and the index of the value that needs to be placed but the output will be the value in the vector.

How do I change an element to a vector in R?

Replace the Elements of a Vector in R Programming – replace() Function. replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.


1 Answers

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.

like image 174
Davit Sargsyan Avatar answered Sep 21 '22 23:09

Davit Sargsyan