0

Further questioning on a question I asked yesterday.

    Year    CW  PIECE       n
1   2018    31  Y5 A        11
2   2018    32  Y5 A        1   
3   2018    33  Y5 A        2
4   2018    36  Y5 B        25
5   2018    37  Y5 B        5

Again I have quite a large dataset. Is there a simple way to loop through this to see -- For each unique value of "PIECE" (So for this small sample it would be average the Y5 A values to get 4.67 and Y5 B get 15) to average the values in column "n"

amstergc20
  • 117
  • 1
  • 11

1 Answers1

1

Try this using dplyr. You can group by PIECE and then use mutate():

library(dplyr)
#Code
newdf <- df %>% group_by(PIECE) %>% mutate(Mean=mean(n,na.rm=T))

Output:

# A tibble: 5 x 5
# Groups:   PIECE [2]
   Year    CW PIECE     n  Mean
  <int> <int> <chr> <int> <dbl>
1  2018    31 Y5 A     11  4.67
2  2018    32 Y5 A      1  4.67
3  2018    33 Y5 A      2  4.67
4  2018    36 Y5 B     25 15   
5  2018    37 Y5 B      5 15   

Or summarise():

#Code2
newdf <- df %>% group_by(PIECE) %>% summarise(Mean=mean(n,na.rm=T))

Output:

# A tibble: 2 x 2
  PIECE  Mean
  <chr> <dbl>
1 Y5 A   4.67
2 Y5 B  15  
Duck
  • 39,058
  • 13
  • 42
  • 84