In the mtcars
sample there are partially matching car names (in Mercedes there are Merc 240D, Merc 230, Merc 280, Merc 280C, Merc 450SE, Merc 450SL, Merc 450SLC
etc).
I would like to group them with the beginning of their name like Merc 2*
and Merc 4*
, count the sum of their hp
by these groups and transform all the mentioned rows into rows called Merc 2
and Merc 4
leaving other non-Mercedes car rows in mtcars
unmodified.
What is the best way of doing this?
Actually the only solution I have to date is:
mtcars %>%
rownames_to_column(var = "cars") %>%
select(cars, hp) %>%
mutate(hp = if_else(cars=="Merc 450SLC",
sum(hp[which(.$cars == "Merc 450SL")], hp[which(.$cars == "Merc450SE")], hp[which(.$cars == "Merc 450SLC")]),
hp))
Many thanks