简体   繁体   中英

using functions inside a for loop in R

I have seen a lot of this close to this but nothing has actually solved the issue I am running into. So my question is how do you address the vector value within a function such as a mean function, and how could you place the vector value into a title. I recently switched from SAS to R so im a little confused.

###### parameters #####
nphase1=50
nphase2=1000
varcount=5
meanshift= 0
sigmashift= 1


##### phase1 dataset/ control limits #####

for (i in 1:varcount)
{
  assign (paste("x",i, sep=""), (rnorm(nphase1,0,1)))
  mean_var[i]=mean(x[i])
  std_var[i]=sd(x[i])
  Upper_SPC_Limit_Method1_var[i]= mean_var[i] + (3 * std_var[i])
  Lower_SPC_Limit_Method1_var[i]= mean_var[i] - (3 * std_var[i])
  moving_range_var[i]= abs(diff(x[i]))
  MR_mean[i]= mean(moving_range_var[i])
  Upper_SPC_Limit_Method2_var[i] =mean_var[i] + (3 * MR_mean[i])
  Lower_SPC_Limit_Method2_var[i] =mean_var[i] - (3 * MR_mean[i])
}

I am sure i will have to do something similar to the (assign(paste("x",i, sep="") for labeling individual the individual limits, but i can't get to that step without being able to calculate the mean of each variable inside the for loop. what i am trying to do is create 5 variables that have 50 observations each(normal random dist). I want to take the mean & Sd of each variable to construct control limits using these numbers.

Thanks for your insight!

Your variables aren't named x[1] , x[2] , etc. They would be x1 , x2 , and so on. You should probably create a list if that's what you want to do, ie x[[i]] <- rnorm(nphase1, 0, 1) , but still your code is inefficient. You should look into vectorizing it, making x a matrix, etc.

I believe the code below accomplishes what you desire. I make use of matrix(), with() and apply(), and strongly recommend reading up on them for this kind of work.

Apply() Tutorial

With() Primer

###### parameters #####
nphase1=50
nphase2=1000
varcount=5
meanshift= 0
sigmashift= 1


##### phase1 dataset/ control limits #####

x <- matrix(rnorm(nphase1*varcount, 0, 1), nrow = nphase1, ncol = varcount)
mean_var <- apply(x, 2, mean)
std_var <- apply(x, 2, sd)
df_var <- data.frame(mean_var, std_var)
Upper_SPC_Limit_Method1_var <- with(df_var, mean_var + 3 * std_var)
Lower_SPC_Limit_Method1_var <- with(df_var, mean_var - 3 * std_var)
moving_range_var <- apply(x, 2, function(z) abs(diff(z)))
MR_mean <- apply(moving_range_var, 2, mean)
Upper_SPC_Limit_Method2_var <- with(df_var, mean_var + 3 * MR_mean)
Lower_SPC_Limit_Method2_var <- with(df_var, mean_var - 3 * std_var)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM