s-news
[Top] [All Lists]

Re: List question

To: Dave Evens <devens8765@yahoo.com>
Subject: Re: List question
From: Prof Brian Ripley <ripley@stats.ox.ac.uk>
Date: Wed, 17 Aug 2005 15:15:48 +0100 (BST)
Cc: s-news@lists.biostat.wustl.edu
In-reply-to: <20050817133836.27911.qmail@web61317.mail.yahoo.com>
References: <20050817133836.27911.qmail@web61317.mail.yahoo.com>
On Wed, 17 Aug 2005, Dave Evens wrote:



Dear all,

My query involves a list. For example, suppose I have
a list x

x <- list(list(rpois(100,2), list(LETTERS[1:20]),
list()),
         list(rpois(150,2), list(LETTERS[1:12]),
list()),
         list(rpois(200,2), list(LETTERS[1:19]),
list()))


and I want to replace the empty list in each sub-list
of x, this is easy using the for-loop

for(k in 1:length(x)) x[[k]][[3]] <- matrix(rnorm(100,
10, 2), 10,10)

but how do I the equivalent of this using the lapply
command?

This is the syntax of the lapply command

lapply(1:length(x), function(k) matrix(rnorm(100, 10,
2), 10,10))

but how do I get it in x[[k]][[3]]?

The closest equivalent would seem to be:

x <- lapply(x, function(k) {
    k[[3]] <- matrix(rnorm(100,10, 2), 10,10)
    k
})

Note that this returns a new list with the changes made.

--
Brian D. Ripley,                  ripley@stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

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