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

Moving part of string separated by semicolon from one column to another

df1:

meats <- c("steak;apples", "ham;pears", "chicken;bananas")

fruit <- c("","","")

I want to extract the fruit part of the string from the ‘meats’ column and move it to the corresponding fruit column but only where there is an empty field in the fruit column. My data frame is actually much bigger and not all values are missing from the ‘fruit’ column.

So I would end up with this:

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

meats <- c("steak", "ham", "chicken")

fruit <- c("apples", "pears", "bananas")

I have tried using an ifelse statement but I am not sure how to combine it with gsub to extract the portion of the string I need and keep both columns properly formatted. I thought about using gsub first to extract the fruit part of the string and then append in the new column but I am wondering if there is a more elegant way to do this.

>Solution :

It is not clear from your example how you want to combine the fruits in meats with the fruits in fruit, but based on your actual example:

split <- strsplit(meats, ";")
meats <- sapply(split, "[", 1)
fruit <- sapply(split, "[", 2)
meats
# [1] "steak"   "ham"     "chicken"
fruit
# [1] "apples"  "pears"   "bananas"

If fruit is being combined with another vector, you will need to explain how you want that merge to happen.

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