Facing problem to change dataframe structure due to special characters

Viewed 27

My Input Data set is

df1 = data.frame(Var_A = c('A&B X+Y','C S'),
                 Var_B = c('1,2','2'))

Desired Output is

df2 = data.frame(Var_A = c('A&B','A&B','X+Y','X+Y','C S'),
                 Var_B = c('1','2','1','2','2'))

Presence of special character such as "&","+" and Space is posing problem

The code I am using is

test_new = separate_rows(df1, "Var_B", convert = FALSE) %>%
  separate_rows("Var_A") %>%
  arrange(Var_A)
1 Answers

We can specify the sep in separate_rows with a regex lookaround

df1 %>% 
   separate_rows(Var_B) %>% 
   separate_rows(Var_A, sep= "(?<=[A-Z]) (?=[A-Z][+])") %>%
   arrange(Var_A)
Related