Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate column with conditions Using R

i have dataset for meals have visitor, meal, meal_code, some meal rows have both meal and meal_code and the meal_code filled from the above row.

The 2nd row contain the issue.

visitor meal meal_code
ahmed water w1
ahmed s1 sandwich w1
khaled fish f1
khaled 2extra coffee c2

I want move the meal_code from meal if have code and fill right. Note that some meal name have number and all meal_code must have number.

I have tried sep = "\\\\s(?=.\*\\\\d) but not work.

like image 973
Abdullah Al Sobhi Avatar asked Sep 14 '25 21:09

Abdullah Al Sobhi


1 Answers

As you said the meal codes could be c2 or c2.1, you can try the following stringr solution:

library(dplyr)
library(stringr)

df %>%
  mutate(meal_code = coalesce(str_extract(meal, "[a-z]+[0-9.]+"), meal_code),
         meal = str_squish(str_remove(meal, meal_code)))

# # A tibble: 4 × 3
#   visitor meal          meal_code
#   <chr>   <chr>         <chr>    
# 1 ahmed   water         w1       
# 2 ahmed   sandwich      s1       
# 3 khaled  fish          f1       
# 4 khaled  2extra coffee c2
like image 51
Darren Tsai Avatar answered Sep 16 '25 14:09

Darren Tsai