Adding a new column to a table

This is an example data with what I am working with:


tibble::tribble(
     ~item, ~quantity,
     "saw",        2L,
     "saw",        4L,
     "saw",        6L,
  "hammer",        1L,
  "hammer",        2L,
  "hammer",        3L
  )

I want to calculate mean for each item and create a new column that shows it

this is what I am trying to get:

tibble::tribble(
     ~item, ~quantity, ~mean,
     "saw",        2L,    4L,
     "saw",        4L,    4L,
     "saw",        6L,    4L,
  "hammer",        1L,    2L,
  "hammer",        2L,    2L,
  "hammer",        3L,    2L
  )

I tried this:

df <- df %>% 
  group_by(item) %>%
  mutate(
    mean = mean(quantity) 
  ) %>%
  ungroup()

but something is not working

Based on what you've provided I was able to reproduce what you were trying to get.

library(dplyr)

df <- tibble::tribble(
     ~item, ~quantity,
     "saw",        2L,
     "saw",        4L,
     "saw",        6L,
  "hammer",        1L,
  "hammer",        2L,
  "hammer",        3L
  )

# Using dplyr pipes
df <- df %>%
  group_by(item) %>%
  mutate(mean = mean(quantity)) %>%
  ungroup()

Output

# A tibble: 6 x 3
  item   quantity  mean
  <chr>     <int> <dbl>
1 saw           2     4
2 saw           4     4
3 saw           6     4
4 hammer        1     2
5 hammer        2     2
6 hammer        3     2

Could it be that other packaged are intervening and messing the result up?

Possible.

Did you receive an error when you ran this particular section?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.