Boris
Boris

Reputation: 63

Using tapply to get means of different columns of a dataframe

So for an assignment I have to put 3 normal distributions in a dataframe, and then calculate 3 means by using 'tapply'. I have no idea why this is giving me a lot of values instead of just 1 mean.

Can anyone help me out?

x <- seq(1,100)
s1 <- dnorm(x, mean = 61, sd = 63)
s2 <- dnorm(x, mean = 38, sd = 5)
s3 <- dnorm(x, mean = 355, sd = 58)

df <- data.frame(s1,s2,s3)

means <- tapply(df$s1, df$s1, mean)

Upvotes: 0

Views: 127

Answers (1)

Lucca Nielsen
Lucca Nielsen

Reputation: 1894

Solved this chaning the data format to long

df <- data.frame(x,s1,s2,s3) %>%
        pivot_longer(cols = -x)

value <- df$value
name <- df$name

means <- tapply(value, name, mean)

means

Output

          s1           s2           s3 
5.662221e-03 1.000000e-02 5.719782e-08 

Upvotes: 1

Related Questions