0

I want to make a loop that uses a different variable each time the loop repeats. Let's say I have 3 different variables: x, y, and z:

x <- 1
y <- 2
z <- 3

I want to perform the same calculation on x, y, and z. I want to multiply by 2:

B <- A*2

Before each loop, I want A to be set equal to the new variable. The long way to do this would be to write it all out manually:

A <- x
B <- A*2
A <- y
B <- A*2
A <- z
B <- A*2

I want to the result to be a vector of this form.

C <- c(2,4,6)

My calculation and variables are much longer than the ones I've shown here, so writing it out manually would make my code very messy. I would prefer to use a loop so I only have to write the calculation once.

1
  • Check out help("mapply") as in mapply('*', list(x, y, z), list(2)). Commented Aug 23, 2018 at 18:48

2 Answers 2

2

Often you can avoid loops by storing things in a list and calling a function from the apply family:

mylist <- list(x, y, z)
sapply(mylist, function(x) x*2)

Notice that this is simple and useful if your variables are in a dataframe:

df <- data.frame(x, y, z)
sapply(df, function(x) x*2)
Sign up to request clarification or add additional context in comments.

Comments

0

This is basic R programming, and can be solved with a form of *apply.

Start by putting your variables in a list.

x <- 1
y <- 2
z <- 3

my_list <- list(x, y, z)

First, the mapply in my comment. It's not strictly necessary to assign a new function, this is just to use a function, f, that looks like a function. The function '*' does not.

f <- `*`    # assign the function '*' to function f

mapply(f, my_list, list(2))
#[1] 2 4 6

Another way would be to use lapply or sapply. Read the help page (it's the same for both these forms of *apply).

g <- function(v){
    2*v
}

sapply(my_list, g)
#[1] 2 4 6

lapply(my_list, g)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.