0

Here is my data:

x <- rnorm(0,1, n = 6)
class <- c(1,1,1,2,2,2)
df <- cbind(x, class)

I want to calculate the mean of x by class and have them repeat for all rows (I get a new column with the means for each class repeated so that the number of rows of the data frame remain the same.

Muhammad Kamil
  • 635
  • 2
  • 15

2 Answers2

4

We can use

library(dplyr)
df <- df %>%
    group_by(class) %>%
    mutate(Mean = mean(x)) %>%
    ungroup

-ouptut

df
# A tibble: 6 x 3
        x class    Mean
    <dbl> <dbl>   <dbl>
1  2.43       1  1.05  
2  0.0625     1  1.05  
3  0.669      1  1.05  
4  0.195      2 -0.0550
5  0.285      2 -0.0550
6 -0.644      2 -0.0550

data

df <- data.frame(x, class)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

A base R option using ave

transform(
    df,
    Mean = ave(x, class)
)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81