Home > Software design >  Paste string into preceding column if no match is found
Paste string into preceding column if no match is found

Time:01-10

I have a dataframe that roughly looks like this:

Col1      Col2     Col3
listerine DB0076 
listerine DB0076
nicotine  Acetate  DB0071

I want the dataframe to look like this. Essentially asking, if there is no DB in the second column, paste it to Col1 in that row.

Col1               Col2
listerine          DB0076 
listerine          DB0076
nicotine Acetate   DB0071

How can I achieve this?

CodePudding user response:

Here a tidyverse approach.

Data

df <-
  structure(list(Col1 = c("listerine", "listerine", "nicotine"), 
                 Col2 = c("DB0076", "DB0076", "Acetate"),
                 Col3 = c(NA, NA,"DB0071")), class = "data.frame", row.names = c(NA, -3L))

Code

library(dplyr)
library(stringr)

df %>% 
  mutate(
    Col1 = if_else(!str_detect(Col2,"DB"), paste(Col1,Col2),Col1),
    Col2 = if_else(!str_detect(Col2,"DB"), Col3,Col2)
  ) %>% 
  select(-Col3)

Output

              Col1   Col2
1        listerine DB0076
2        listerine DB0076
3 nicotine Acetate DB0071
  • Related