I have a vector like this: 1=cat, 2=dog,3=duck,4=chicken, 5=donkey
animal_type<-c("1", "1 2","1 2 3","1 2 3 4", "1 2 3 4 5", "1 2 3 5","1 2 4","1 2 4 5","1 2 5","1 3")
Now, instead of this combination value, I want to convert them in to category based on each animal type, which ideally looks like (the number in column "count" is just made up, not the correct number based on the dataset):
animal_type count
cat 3
dog 6
duck 7
chicken 4
donkey 3
or instead of animal’s name, just like this:
animal_type count
1 3
2 6
3 7
4 4
5 3
My question is whether there is an efficient way to achieve this goal in R ? Thanks a lot~~!
>Solution :
We may use separate_rows to split the column, then use the index to change the values to animal names and do a group by summarise or use count
library(dplyr)
library(tidyr)
df %>%
separate_rows(animal_type, convert = TRUE) %>%
group_by(id, animal_type = c('cat', 'dog', 'duck', 'chicken', 'donkey')[animal_type]) %>%
summarise(count = n())