0

I hope someone can help with this problem.

I essentially have a dataframe with around 9,000 observations of 18 variables (some character, some numeric). One of the numeric variables is 'rating', which varies from 50 to 110. One of the character variables is 'name'. In the dataframe there are about 700 unique names, but the amount of data for each name is different (e.g. 'Tony' might have eight entries, and eight different ratings, whereas 'Sue' might only have three).

I have used tapply to return another dataframe of the mean and maximum 'rating' for each 'name' and now wish to add these values to all entries by name in my original dataframe.

How can I do that?

Thomas Deane
  • 35
  • 1
  • 3
  • 1
    in general, you are most likely to get help if you post a reproducible example https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example. You can share part of data using dput – desval May 01 '20 at 16:19

1 Answers1

0

There is no need to create an additional data.frame and merge it back.

Using dplyr:

library("dplyr")
d <- d %>%
  group_by(Name) %>%
  mutate( min = min(Rate1),
          max = max(Rate1))

# A tibble: 9 x 6
# Groups:   Name [3]
  Name  Month Rate1 Rate2   min   max
  <fct> <int> <int> <int> <int> <int>
1 Aira      1    12    23    12    19
2 Aira      2    18    73    12    19
3 Aira      3    19    45    12    19
4 Ben       1    53    19    19    53
5 Ben       2    22    87    19    53
6 Ben       3    19    45    19    53
7 Cat       1    22    87    22    67
8 Cat       2    67    43    22    67
9 Cat       3    45    32    22    67

Using data.table

library("data.table")
d <- setDT(d)
d[, mean := mean(Rate1), by=Name]
d[, max := max(Rate1), by=Name]

Data:

d <- read.table(text=
                  'Name     Month  Rate1     Rate2
Aira       1      12        23
Aira       2      18        73
Aira       3      19        45
Ben        1      53        19
Ben        2      22        87
Ben        3      19        45
Cat        1      22        87
Cat        2      67        43
Cat        3      45        32', header=TRUE)
desval
  • 2,345
  • 2
  • 16
  • 23