I'm generating a set of densities using functions like dweibull and dunif. I'd like to be able to extract their moments using sapply. When I call the mean function on individual distributions, I get the mean value as expected. But when I do this with sapply, instead it seems to call mean() on every individual value in the density (i.e. for every value of x I supplied to dweibull or dunif. Is there a way to get the correct behavior here? Thank you!
weib <- dweibull(seq(from=0, to=25, length=100), shape=1, scale=5)
unif <- dunif(seq(from=1, to=10, length=100), min=1, max=10)
mean(weib) #Works!
dists <- c(weib, unif)
means <- sapply(dists, mean) #Returns a very long list of values, not the mean of weib and unif
CodePudding user response:
You should store the data in a list. c(weib, unif)
creates a single combined vector and using sapply(dists, mean)
returns the mean of single number i.e the number itself.
dists <- list(weib, unif)
means <- sapply(dists, mean)
CodePudding user response:
You can also use dataframe
dists <- data.frame(weib, unif)
sapply(dists, mean)
weib unif
0.04034828 0.11111111
lapply(dists,mean)
$weib
[1] 0.04034828
$unif
[1] 0.1111111
apply(dists, 2,mean)
weib unif
0.04034828 0.11111111