I have a dataframe, df:
df <- data.frame(a = c("b2","d2","a1","c1"), b = c(12, 3, 54, 4))
> df
a b
1 b2 12
2 d2 3
3 a1 54
4 c1 4
And an external vector, that I would like the order of a
to match:
vec <- c("a1","b2","c1","d2")
Normally I can do this as follows using match
:
df <- df[match(vec, df$a),]
> df
a b
3 a1 54
1 b2 12
4 c1 4
2 d2 3
However, I would like to know if there is a way to do this in dplyr. I have tried the following, but it did not work:
df <- df %>%
mutate(
a = match(vec, a)
)
> df
a b
1 3 12
2 1 3
3 4 54
4 2 4
Can anyone suggest where I'm going wrong in my code?