[R] row, col function but for a list (probably very easy question, cannot seem to find it though)

David Winsemius dwinsemius at comcast.net
Tue Mar 27 17:29:08 CEST 2012


On Mar 27, 2012, at 3:37 AM, peter dalgaard wrote:

>
> On Mar 26, 2012, at 17:33 , David Winsemius wrote:
>
>> The usual approach to that problem is to use sapply:
>>
>> x <- list()
>> x <- sapply(1:10, function(z) x[[z]] <- 1:z )
>
> Yikes!
>
> If that works, it is only by coincidence.... (The pre-assignment to  
> x only serves the purpose of allowing the "[["-assignment inside the  
> anonymous function, but the assignment is to a local copy which is  
> deleted on exit, and the return value is the rhs of the assignment.)

Well, maybe not by pure coincidence. There are really two rhs's and it  
was because of the outer assignment of the values to 'x' that it  
worked as intended. My error is in propagating the notion that  
assignments to named objects inside the function will survive outside  
the function.

 > x <- list(); y<-list()
 > y <- sapply(1:10, function(z) x[[z]] <- 1:z )
 > x
list()


>
> Please:
>
> x <- lapply(1:10, function(z) 1:z)
>
> or even
>
> x <- lapply(1:10, seq_len)

Yes, I see the error of my ways. I wonder how many times I have been  
in this state of sin in the past?

>
> -- 
> Peter Dalgaard, Professor
> Center for Statistics, Copenhagen Business School
> Solbjerg Plads 3, 2000 Frederiksberg, Denmark
> Phone: (+45)38153501
> Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com
>

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list