How to create new variable at the end of each loop iteration in R

r loop through list of variables
for loop with two variables in r
for loop in r
for loop in r data frame
create multiple dataframes loop r
nested for loop in r
while loop in r
store for loop values in array r

I am trying to create a variable that is a function of 4 other variables. I have the following code:

set.seed(123)
iter <- 1000
group <- c('A','B','C','D','E','F')
for (i in group) {
  df <- df1[df1$group == i,]
  x_ <- vector(mode="numeric", length=1000)
  assign(eval(paste0("X_", i)), globalenv())   #This is the issue

  a <- rnorm(iter, mean=df$a, sd=df$sea)
  b <- rnorm(iter, mean=df$b, sd=df$seb)
  c <- rnorm(iter, mean=df$c, sd=df$sec)
  z <- rnorm(iter, mean=df$zbar, sd=df$se_z)

  X_[i] = (a + c*(z-df$zbar))/(-b)
}

I am unable to create a unique group-specific variable (e.g. X_A, X_B, ...) and I am unsure why the -assign( )- function is not working properly. The dataframe df1 has 6 rows (one for each group) and then the number of columns is equal to the number of variables plus a string variable for group. I am not trying to append this new variables X_[i] to the dataset I am just trying to place it in the global environment. I believe the issue lies in my assigning the placement of the variable, but it isn't generating a numeric variable X.

df1 is a dataframe with 6 observations of 9 variables containing a, sea, b, seb, c, sec, zbar, se_z. These are just the means and standard deviations of a, b, c, and z, respectively. The 9th variable is group which contains A, B, ..., F. When I use the code df <-df1[df1$group == i,] I am trying to create a unique X variable for each group entity.

Try something like this:

dynamicVariableName <- paste0("X_", i)
assign(dynamicVariableName, (a + c*(z-df$zbar))/(-b))

21 Iteration, This is very important for efficiency: if you grow the for loop at each iteration using A general way of creating an empty vector of given length is the vector() function. to a more complex result object, and then combine in one step at the end. to make sure that the numbers lined up nicely, even though the variable names� Some loops execute for a prescribed number of times, as controlled by a counter or an index, incremented at each iteration cycle. These are part of the for loop family. On the other hand, some loops are based on the onset and verification of a logical condition. The condition is tested at the start or the end of the loop construct.

Alternatively to the answer from @ErrorJordan, you can write your loop like that:

set.seed(123)
iter <- 1000
group <- c('A','B','C','D','E','F')
for(i in group)
{
  df <- df1[df1$group == i,]

  a <- rnorm(iter, mean=df$a, sd=df$sea)
  b <- rnorm(iter, mean=df$b, sd=df$seb)
  c <- rnorm(iter, mean=df$c, sd=df$sec)
  z <- rnorm(iter, mean=df$zbar, sd=df$se_z)

  X <- (a + c*(z-df$zbar))/(-b)
  assign(paste0("X_",i),X,.GlobalEnv)
}

As suggested by @MrFlick, you can also stored your data into a list, to do so you can just modify your loop to get:

set.seed(123)
iter <- 1000
group <- c('A','B','C','D','E','F')  
X = vector("list",length(group))
names(X) = group
for(i in 1:length(group))
{
  df <- df1[df1$group == group[i],]    
  a <- rnorm(iter, mean=df$a, sd=df$sea)
  b <- rnorm(iter, mean=df$b, sd=df$seb)
  c <- rnorm(iter, mean=df$c, sd=df$sec)
  z <- rnorm(iter, mean=df$zbar, sd=df$se_z)

  X[[i]] <- (a + c*(z-df$zbar))/(-b)
}

df1 dataframe

df1 = data.frame(a = c(1:6),
                 b = c(1:6),
                 c = c(1:6),
                 zbar = c(1:6),
                 sea = rep(1,6),
                 seb = rep(1,6),
                 sec = rep(1,6),
                 se_z = rep(1,6),
                 group = group)

Loops in R – Programming with R, Instead of using i in a to make our loop variable, we use the function seq_along to When R reaches the end of the shorter vector b , it starts again at the first element of b and Note how we add a new column to out at each iteration? This is a� In each round through the loop, add the outcome of switch() at the end of the vector VAT. The result is a vector VAT that contains, for each client, the correct VAT that needs to be applied. You can test this by adding, for example, a variable type to the data frame clients you created in the previous section like this:

It's a little hard to parse what you want to do, but I'm assuming it's something like

for each value in group make an object (in the global env) called X_A, X_B, ...

for each one of those objects, assign it the value (a + c*(z-df$zbar))/(-b)

I think this should do that for you:

set.seed(123)
group <- c('A','B','C','D','E','F')
for (i in group) {
  df <- df1[df1$group == i,]

  a <- rnorm(iter, mean=df$a, sd=df$sea)
  b <- rnorm(iter, mean=df$b, sd=df$seb)
  c <- rnorm(iter, mean=df$c, sd=df$sec)
  z <- rnorm(iter, mean=df$zbar, sd=df$se_z)

  assign(paste0("X_", i), (a + c*(z-df$zbar))/(-b), globalenv())
}

Note that in the code example you gave, the command iter <- 1000 has no effect, and the command x_ <- vector(mode="numeric", length=1000) also has no effect. By that I mean, you make those objects, but never subsequently use them in any further computation. If those commands should do something meaningful I'll need your help in explaining their intended purpose.

Loops and Functions in R, Make decisions with if and else statements; Use a for loop to repeat operations; Incorporate functions to repeat Using the names above, each iteration of variable takes the value of one of the elements of vector . …and end of that list:. Creating a new variable in each iteration. Learn more about variable creation in a loop

A Tutorial on Loops in R - Usage and Alternatives, A tutorial on loops in R that looks at the constructs available in R for looping. of times, as controlled by a counter or an index, incremented at each iteration cycle. on a variable which can assume values within a specified sequence. Note that you had to set a condition within the loop upon which to exit� On each loop I would like the variable to change so I can retrieve the data for each loop at a later point. Also, I would like to be able to repeat this method for other data frames and in creating these new data frames, it draws upon other data frames based on the iteration it is on.

For-loops in R, In many programming languages, a for-loop is a way to iterate across a sequence where the variable var successively takes on each value in sequence . In R, the command 0:3 will create a vector with the numbers from 0 to 3, as you can� In this case, you end up with the variable s, a structure, containing fields specified by the strings stored in the cell array names. Now, if you still really want to create variables with dynamically generated names, you need to use EVAL.

Looping in R, tested at the start ( while ) or at the end ( repeat ) of the loop construct. Say we wanted to scale and center each variable in the air.data dataset. We can iterate the process over of each column of the dataframe in a number of ways. mat = matrix(nrow=5, ncol=5) # create a 30 x 30 matrix (of 30 rows and� Plus you can easily assign new values for the matrix and list versions, but for the get/assign version you'd need a temporary variable. – cbeleites unhappy with SX May 15 '13 at 13:58 fortunes::fortune(236) : The only people who should use the assign function are those who fully understand why you should never use the assign function.

Comments
  • Can you precise what is df1 and crop ? and also provide a reproducible example of df1 if df1 is a dataframe
  • I have updated the question, thank you for pointing this out
  • This is a bad design patter in R. Rather than pasting data in to names of variables, store values in a named list. This makes things much, much easier to work with in R. get()/assign() should generally be avoided
  • Iter is used at the beginning of each random variable generation as the number of observations, the vector one is not used though thanks for pointing that out