s-news
[Top] [All Lists]

Re: problem with workbench

To: Dave Evens <devens8765@yahoo.com>, s-news@lists.biostat.wustl.edu
Subject: Re: problem with workbench
From: "Richard M. Heiberger" <rmh@temple.edu>
Date: Thu, 16 Jun 2005 13:57:14 -0400
## I reformatted your example to isolate the function definition.

data1 <- vector(mode="list", length=10)
names(data1) <- paste(LETTERS[1:10])             
data1 <- lapply(1:length(data1),

                function(k) {
                  data1[[k]] <- k
                  data1[[k]]
                }
                
                )

## Notice that data1 is not in the argument list.  Therefore it is
## using the globally defined object.  S-Plus allows you to read a
## global object from within a function, but it does not allow you to
## change a global object from within a function.


## Look very closely at the documentation for the apply family of
## functions.  This example from ?lapply in S-Plus 7.0 shows how to use
## additional arguments.
## 
## # To operate on two lists let X be a vector of indices
## list1 <- lapply(1:6, runif)  # artificial data for this example
## list2 <- lapply(1:6, runif)
## lapply(1:6, function(i, x, y) x[[i]] + y[[i]],
##        x = list1, y = list2)


## The correct way to use lapply for the specific trivial example you
## asked about is this:

   result <- lapply(LETTERS[1:10], function(k) k)
   result
   names(result) <- LETTERS[1:10]
   result

## Notice that lapply itself created the list.  You don't have to do it.

<Prev in Thread] Current Thread [Next in Thread>