Hello,
I'm trying to divide multiple vectors by a ratio in a for loop using the get function. Here is an example:
a <- c(1, 2)
b <- c(10,12)
u <- c("a", "b")
n <- length(u)
k <- 1.1
i <- 1
for (i in 1:n) {
get(u[i]) <- get(u[i])*k
}
I've used get for these types of things but it doesn't seem to work on the left.
This is the error:
Error in get(u[i]) <- get(u[i]) * k : could not find function "get<-"
How can I fix this?
I want to keep a and b as separate variables and not do some kind of split function. And this seemed like a logical way of solving it.
Thank you!!
You can not use get to assign a value. Use assign for that purpose.
a <- c(1, 2)
b <- c(10,12)
u <- c("a", "b")
n <- length(u)
k <- 1.1
i <- 1
c(a, b)
#> [1] 1 2 10 12
for (i in 1:n) {
assign(u[i], get(u[i])*k)
}
c(a, b)
#> [1] 1.1 2.2 11.0 13.2
It worked thank you!
I'd rather use it in a for-loop because I'll be doing it for many variables. This was just an example. And those variables are already in the c("a", "b") format.