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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With