[R] Defining a "list"

Rolf Turner r.turner at auckland.ac.nz
Wed Oct 15 23:28:42 CEST 2008


On 16/10/2008, at 12:28 AM, Henrique Dallazuanna wrote:

> Try this:
>
> lapply(1:n, rnorm)

That has nothing to do with what the inquirer *asked*.

>
> On Wed, Oct 15, 2008 at 8:19 AM, Megh Dal <megh700004 at yahoo.com>  
> wrote:
>
>> Can anyone please tell me how to define a "list". Suppose I want  
>> to define
>> a list object "result" with length n then want to fill each place of
>> "result" with different objects. For e.g.
>>
>> i=1

	Why have you set i=1?  You make no use at all of ``i''!!!

>> result[1] = rnorm(1)
>>
>> i=2
>> result[2] = rnorm(2)
>>
>> .......................
>>
>> i=n
>> result[n] = rnorm(n)
>>
>> What would be the best way to do that?

Simply start off with

	result <- list()

Then you can do

	result[[1]] <- rnorm(1)
	result[[2]] <- rnorm(2)
	result[[42]] <- "a load of dingos' kidneys"

Note 1:  This will result in a list of length (at this stage) 42.
Entries 3 to 41 inclusive of this list will be NULL.

Note 2:  Use the ***double*** brackets!  The distinction is that
if result is a *list* then

	result[1] is a ***list*** of length 1, the sole entry of that
	list being the first entry of result

	result[[1]] is the first entry of result, pure and simple.

If you tried

	result[2] <- rnorm(2)

you'd get a warning message about the wrong number of items to replace
(you have tried to assign something of length 2 to something of  
length 1)
and result[[2] would contain only the first entry of the vector rnorm 
(2).

	cheers,

		Rolf Turner

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}



More information about the R-help mailing list