I have a tibble like this
library("tidyverse")
tib <- tibble(x = c("lemon", "yellow, banana", "red, big, apple"))
I would like to create two new columns named description and fruit and extract the last word after the comma using separate (if there is a comma; otherwise, I would like to just copy the word in the cell).
So far, I have
tib %>%
separate(x, ", ", into = c("description", "fruit"), remove = FALSE)
but this doesn't quite do what I want, yielding:
# A tibble: 3 x 3
x description fruit
<chr> <chr> <chr>
1 lemon lemon NA
2 yellow, banana yellow banana
3 red, big, apple red big
Warning messages:
1: Expected 2 pieces. Additional pieces discarded in 1 rows [3].
2: Expected 2 pieces. Missing pieces filled with `NA` in 1 rows [1].
The output I want is:
x description fruit
1 lemon NA lemon
2 yellow, banana yellow banana
3 red, big, apple red, big apple
Can someone point me to the part I'm missing?
EDIT
The goal doesn't have to be achieved using separate. mutate would also work, and solutions are equally appreciated!