0

I need to make loop that assigns new values to certain vectors based on vector of vectors names. Overall, it can be easily done just by using assign. Here is an example:

set.seed(11)
my_future_vectors=c("vec1","vec2","vec3")
for (i in 1:length(my_future_vectors)){assign(my_future_vectors[i],runif(3,0:1))}

The problem with assign is that whenever I need to add new values to those vectors it overwrites them. If I want add 1 and I do:

assign(my_future_vectors[1],1)

Than:

> vec1
[1] 1

This is understandable, but what works for me is vec1[length(vec1)+1]=1, which gives output:

> vec1
[1] 0.2772497942 1.0000000000 0.0005183129 1.0000000000

Problem arises whenever i try to use function get to address certain vector:

get(my_future_vectors[1])[length(my_future_vectors[1])+1]=1

I get an error:

Error in get(my_future_vectors[1])[length(my_future_vectors[1])] = 1 : 
  could not find function "get<-

So I understand that get doesnt work this way, so I have no idea how make a loop like that. Please provide solution or workaround to avoid this error. Or am I missing something obvious here?

Alexandros
  • 331
  • 1
  • 14
  • You need a close parentheses. Read the error, it is looking for a function called "get<-", because you didn't type the final parentheses of get() – leeum Mar 27 '18 at 16:37
  • 5
    Why are you using `get()/assign()` at all here? Rather than have a vector of character names of vectors, why not keep all your values in a named list? This will make things much easier to work with in R. – MrFlick Mar 27 '18 at 16:37
  • More discussion here: https://stackoverflow.com/questions/17559390/why-is-using-assign-bad – MrFlick Mar 27 '18 at 16:38
  • 2
    The use of `get`/`assign` is almost always able to be replaced with (optionally-named) lists or similar constructs, and doing so provides performance gains and promotes a much-more scalable way of thinking about the process as a whole. – r2evans Mar 27 '18 at 16:41
  • 2
    Besides not using get/assign, you should also not dynamically grow vectors in R. For similar hints about good R programming practice, maybe read the R Inferno http://www.burns-stat.com/documents/books/the-r-inferno/ – Frank Mar 27 '18 at 16:43
  • Thank you for your advice, I will make research about lists in R and try to rewrite my current code. Btw, why dynamically growing vectors is wrong in R? It is crucial to huge part of my work... – Alexandros Mar 27 '18 at 16:53
  • See [Chapter 2](https://www.burns-stat.com/pages/Tutor/R_inferno.pdf). – joran Mar 27 '18 at 16:55

0 Answers0