Home > Software design >  Moving part of string separated by semicolon from one column to another
Moving part of string separated by semicolon from one column to another

Time:03-22

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:

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.

CodePudding user response:

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.

  •  Tags:  
  • r
  • Related