I'm attempting to learn how to use base R
instead of tidyverse
code language, and I'm having trouble finding the base
version of the following tidyverse
code:
mydf <- data.frame(level = factor(c("A", rep("B", 2), "A", "B", rep("A", 5), "B")),
group = factor(c("Apple", rep("Pear", 2), rep("Orange", 2), rep("Banana", 4), rep("Cherry", 2))))
library(dplyr)
mutate(group_by(mydf, group, level), value = row_number())
level group value
<fctr> <fctr> <int>
1 A Apple 1
2 B Pear 1
3 B Pear 2
4 A Orange 1
5 B Orange 1
6 A Banana 1
7 A Banana 2
8 A Banana 3
9 A Banana 4
10 A Cherry 1
11 B Cherry 1
How would I create the value
variable above in base R
? I've been playing around with the aggregate
function and the rank
function, but it's not exactly giving me what I'm looking for:
aggregate(mydf$level, by = list(group = mydf$group, level = mydf$level), FUN = rank, ties.method = "first", na.last = "keep")
group level x
1 Apple A 1
2 Banana A 1, 2, 3, 4
3 Cherry A 1
4 Orange A 1
5 Cherry B 1
6 Orange B 1
7 Pear B 1, 2