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!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…