Say I have vectors a1, a2, a3
, and I want to iteratively edit each vector. Normally, you could do something along the lines of
for (i in 1:3) {
assign(paste("a", i, sep=""), ...)
}
However, this would re-assign the entire objects 'a1, a2, a3`. Is there are a way to only edit a single value in each of the vectors without having to copy the entire vectors? Is there an R function that intakes a string and returns the object with that name? get() only returns the value of the object with the inputted name.
I've tried paste("a", i, sep="")[1]
and get(paste("a", i, sep=""))[1]
, but neither of these two options return the object with name "ai".
EDIT: Here is a reproducible example.
a1 = c(1,2,3)
a2 = c(4,5,6)
for (i in 1:2) {
assign(get(paste("a", i, sep=""))[1], 0)
}
Error in assign(get(paste("a", i, sep = ""))[1], 0) :
invalid first argument
My goal is to iteratively change the first element of both vectors to 0. The error arises because get(paste("a", 1, sep = ""))
returns [1] 1 2 3
rather than the object a1
itself.