1

I want to fill a vector through a function, that vector being global in my code:

## The vector
x = c( NA, NA, NA )

## changing its value
x[1] <- 1 # fine
x[1] <<- 1 # not fine

Error in x[1] <<- 1 : object 'x' not found

That must be some very basic R, I cannot see however how to have that value stored globally.

Xavier Prudent
  • 1,570
  • 3
  • 25
  • 54
  • How about `assign` i.e. `assign("x", '[<-'(x, 1, value = 1))` – akrun Sep 16 '16 at 14:34
  • 2
    Can you give a more [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? This works for me: `x <- c(NA, NA, NA);f <- function() {x[1]<<-1};f()`. Are you not really using a function? And just wanted to add a friendly reminder that using global variables in a functional language is not a great idea. – MrFlick Sep 16 '16 at 14:34
  • Why are you not passing the vector to your formula using `function(x)` and then receiving the results back `x<-function(x)`? – Morgan Ball Sep 16 '16 at 14:38
  • It is truely strange, that `<<-` can be used in the console as `x<<-3` but not as `x[1]<<-3`or as `x[[1]]<<-3`. I feel that is unexpected. `help`says "In all the assignment operator expressions, x can be a name or an expression defining a part of an object to be replaced (e.g., z[[1]])." – Bernhard Sep 16 '16 at 14:38
  • 3
    There's no `[<<-` operator but there is a `[<-` operator – hrbrmstr Sep 16 '16 at 14:42
  • 1
    What you want is extremely uncommon and inadvisable. Why do you believe you need this? – Roland Sep 16 '16 at 14:42
  • MrFlick, your way indeed work. My intent in fact is to have a vector, whose content will be changed and accessed in different places of my code. By using x<-function(x), I would rerun "function" each time I need x in a different place. – Xavier Prudent Sep 16 '16 at 20:58

0 Answers0