list =ls()
set.seed(1234)
S<- numeric()
Y_bar <- numeric()
Xsq <- numeric()
T_st <- numeric()
for (i in c(1:10000)) {
sample = rnorm(n= 20, mean=2, sd = 5)
s = var(sample)
S <-append(S,s)
y_bar = mean(sample)
Y_bar<-append(Y_bar,y_bar)
xsq = n-1*s**2/5**2
Xsq <-append(Xsq,xsq)
t_st = y_bar - mean/( as.numeric(s)/sqrt(n))
T_st <-append(T_st,t_st)
}
Error in mean/(as.numeric(s)/sqrt(n)) : non-numeric argument to binary operator
Error in sd^2 : non-numeric argument to binary operator
I need all these calculated values like s
and y_bar
for my later calculations.
CodePudding user response:
My sense is there is some confusion. You are specifying the mean, mean
and sample size n
as parameters in the in the rnorm
function but not assigning them as objects in the global environment. They are not saved (as they would be with mean <- 5
).
Sticking to your original code as much as possible (though this could be optimized), a more proper way to run this loop is to define your sample size, mean, and standard deviation, in the global environment and use that to specify the parameters (then replace accordingly throughout).
set.seed(1234)
S <- numeric()
Y_bar <- numeric()
Xsq <- numeric()
T_st <- numeric()
# specify sample size, mean, and sd
sample_n <- 20
sample_mn <- 2
sample_sd <- 5
for (i in c(1:10000)) {
# specify parameters from those defined in the global environment
sample = rnorm(n = sample_n, mean = sample_mn, sd = sample_sd)
s = var(sample)
S <- append(S, s)
y_bar = mean(sample)
Y_bar <- append(Y_bar, y_bar)
# Change object names accordingly
xsq = sample_n - 1 * s ** 2 / 5 ** 2
Xsq <- append(Xsq, xsq)
t_st = y_bar - sample_mn / (as.numeric(s) / sqrt(sample_n))
T_st <- append(T_st, t_st)
}
Note that I used terms like sample_mn
since mean <- 5
is not good practice since mean()
is already a function.