Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R – How to create a new vector based on the strings in another vector

I am a beginner coding in R.

I am trying to create a vector based on the strings of another vector. Say:

vector_one <- c("A", "B", "C", "D")

I want to create a second vector which reads the strings in vector_one, and connects it to new values. So I guess it would be something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

vector_two <- if vector_one == "A" then vector_two == "apple",
              if vector_one == "B" then vector_two == "banana",
              (and so on)

so that the end result of my vector_two would be:

vector_two <- c("apple", "banana", "cat", "dog")

How can I proceed? Thank you for your help in advance.

I’m stuck beyond words.

>Solution :

You could also use recode or even case_match:

recode(vector_one, 'A' = 'apple', 'B' = 'banana', 'C' = 'cat', 'D' = 'dog')
[1] "apple"  "banana" "cat"    "dog"   

case_match(vector_one, 'A'~'apple', 'B' ~ 'banana', 'C'~'cat', 'D'~'dog')
[1] "apple"  "banana" "cat"    "dog" 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading