0

I want to add a new member to the list. When I do it as follows. But when I want to do it in a function, nothing changes..

> a = list( x=4, y=2)
> a
$x
[1] 4

$y
[1] 2

> a$c = 7
> a
$x
[1] 4

$y
[1] 2

$c
[1] 7

Using a function...

> addNew(a)
> a
$x
[1] 4

$y
[1] 2

The function is:

addNew = function(list){
  list$c = 7
}

Maybe it is kinda problem like pointers in c, but how can solve it?

ibilgen
  • 460
  • 1
  • 7
  • 15

2 Answers2

1

You have to return and assign the modified list:

a <- list(x=4, y=2)
addNew <- function(l) {
  l$c <- 7
  return(l)
}
a <- addNew(a)

EDIT: As @mitra mentioned you could use <<-:

a <- list(x=4, y=2)
addNew <- function() {
  a$c <<- 7
}

But that changes the typical behaviour of a function in R. Most user didn't expect that a function has side effects like changing the global environment.

Please read Patrick Burns' R Inferno (p. 35):

If you think you need <<- , think again. If on reflection you still think you need <<- , think again. Only when your boss turns red with anger over you not doing anything should you temporarily give in to the temptation. There have been proposals (no more than half-joking) to eliminate <<- from the language. That would not eliminate global assignments, merely force you to use the assign function to achieve them.

sgibb
  • 25,396
  • 3
  • 68
  • 74
0

You should look at the difference between local and global variables:

Global and local variables in R

If you define a variable inside a function, it is temporary and belongs to the function only.

check this:

list$c<<-7
Community
  • 1
  • 1
mitra
  • 101
  • 6
  • I tried a global variable also, it wasn't changed. Is there any special way to defien global variable in R? – ibilgen Aug 29 '13 at 08:01
  • list$c <<- 7 is works. Thanks! But you should write the actual variable name as in global, not work via parameter name.. – ibilgen Aug 29 '13 at 08:09