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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With