-1

I have following code

l=list()
funcF=function(x)
{
  l[[x]] ="somevalue"
}

funcF("A")
funcF("B")
print(l)

I was expecting

print(l)

to print

$A
[1] "somevalue"


$B
[1] "somevalue"

but it prints

"list()"

Why the list is empty, if I set the same values outside of the function it works. What am I missing?

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Code Ninja
  • 93
  • 1
  • 8

1 Answers1

1

A function is a closed system. The objects inside the function do not "know" that there is a list l on the outside.

If you want to manipulate an object such as the list l, you have to pass it to that function. Otherwise it is beyond the scope of the function and inaccessible to it.

See what happens if I re-write the function like this:

l=list()
funcF=function(x,y,z)
{
  x[[y]] = z
  return(x)
}

funcF(l,"A","someA")

#> funcF(l,"A","someA")
#$A
#[1] "someA"

funcF(l,"B","someB")

#> funcF(l,"B","someB")
#$B
#[1] "someB"

l <- funcF(l,"A","someA")
l <- funcF(l,"B","someB")
l

#> l
#$A
#[1] "someA"
#
#$B
#[1] "someB"

In the newly written function x is the target list, y denotes the "slot" to be filled, and z is the value that is assigned to the slot.

Cheers!

SimonG
  • 4,701
  • 3
  • 20
  • 31
  • Thanks @SimonG ... this explains it. My function need to return some other value as well, are there out parameters in R? – Code Ninja Aug 30 '14 at 21:23