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.
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)
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)
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.