# get function left of <-

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


Created on 2021-04-09 by the reprex package (v2.0.0)

But if I may ask, why don't you use a * k directly?

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.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.