0

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
Phil
  • 7,287
  • 3
  • 36
  • 66
  • The `by`-function might be what you are looking for. However, note that there is a reason why many do not use `base R` for `split-apply-combine` tasks. – coffeinjunky May 11 '17 at 22:27
  • 1
    `ave(seq_len(nrow(mydf)), mydf[c("group","level")], FUN=seq_along)` - this has been answered here heaps of times before - http://stackoverflow.com/questions/12925063/numbering-rows-within-groups-in-a-data-frame for example. A few duplicates too: http://stackoverflow.com/questions/linked/12925063?lq=1 – thelatemail May 11 '17 at 22:30
  • Or if you need `rank`: `ave(1:nrow(mydf), mydf$level, mydf$group, FUN = rank, ties.method = "first", na.last = "keep")` – Mike H. May 11 '17 at 22:31
  • Sorry @thelatemail. I've made several searches but I didn't use the proper terminology for these posts to show up. Thanks for the help. – Phil May 12 '17 at 00:39
  • @Phil - no problems - a duplicate question is not a big drama and your question was perfect otherwise. – thelatemail May 12 '17 at 00:45

0 Answers0