-2

I use set.seed=(7) and find a random sample of size 4 from the standard normal distribution with replicate(n=100, rnorm(4)) Now I have data 4 rows and 100 column. How can I use the replicate function to run the mean of each column (100 column here)? Also, how I can I use replicate function to run the following formula?

(1/(n-1)(sum((x-mean(x))^2))
jay.sf
  • 60,139
  • 8
  • 53
  • 110
Zee
  • 7
  • 2
  • If you want the mean of the column of what amounts to a data frame or matrix, there are ways to do that. This method with replicate() seems a little contrived and thus seems like a homework type of question. – shea Feb 17 '19 at 16:39
  • It's `set.seed(7)`, not `set.seed=(7)` – jay.sf Feb 17 '19 at 16:44

2 Answers2

0

Just add the mean() into the replicate().

set.seed(7)

replicate(n=100, mean(rnorm(4)))

For your second question, define a function before.

fun <- function(x, n) (1 / (n - 1) * (sum((x - mean(x))^2)))

set.seed(7)
replicate(n=100, fun(x=rnorm(4), n=100))
jay.sf
  • 60,139
  • 8
  • 53
  • 110
0

You can do:

# Create samples
set.seed(7)
my.df <- replicate(n=100, rnorm(4))

# Calculate mean of each column 
means <- apply(my.df, MARGIN = 2, mean)

# Calculate the function of each column (you could also use the function var)
variances <- apply(my.df, MARGIN = 2, FUN = function(x) (1/(length(x)-1) * (sum((x-mean(x))^2))))
kath
  • 7,624
  • 17
  • 32