Home > OS >  For loop with dynamic input
For loop with dynamic input

Time:02-19

I am trying to create a dynamic input that I can easily change that will be used inside a for loop. Inside a for loop that I am using, there is a variable, let's call it b, that is used multiple times, and every time I want to slightly change the value stored in b, I have to go through and find each instance of b and change it. I am hoping to create an input outside of the for loop that I can use to update b inside the for loop.

This is a very simplified example of what I am currently doing.

df <- data.frame(replicate(3,sample(0:100,10,rep=TRUE)))
for (i in c(1:nrow(df))){
  nm <- i
  if (nm == nrow(df)) {
    next
  } else {
    x <- df[c((nm):(nm 1)),]
    b <- x$X1[1]
    print(b > x$X2[2])
  }
}

Here is an example of what I am trying to do, however, in this example the input does not work because dateframe x is not yet created. Some more examples of the inputs could be b <- x$X1[2], b <- x$X2[1], b <- x$X3[2], etc

df <- data.frame(replicate(3,sample(0:100,10,rep=TRUE)))

##input

b <- x$X1[1]

###

for (i in c(1:nrow(df))){
  nm <- i
  if (nm == nrow(df)) {
    next
  } else {
    x <- df[c((nm):(nm 1)),]
    print(b > x$X2[2])
  }
}

I was looking at this post here and it looks like there is a way to achieve what I am trying to do, however, in the post, they assign a value to the variable. In my example, the value stored in b will change in every iteration of the for loop so this method will not work.

CodePudding user response:

It seems like essentially you want to delay the evaluation of the expression for b. As written, x$X1[1] will be evaluated (or at least attempted to be) when b is defined. You can mark it as an expression and evaluate it later. There are some base functions for this but I find rlang often easier to use

##input

b <- rlang::expr(x$X1[1])

###

for (i in c(1:nrow(df))){
  nm <- i
  if (nm == nrow(df)) {
    next
  } else {
    x <- df[c((nm):(nm 1)),]
    print(rlang::eval_bare(b) > x$X2[2])
  }
}

  •  Tags:  
  • r
  • Related