Re: [R] Error with lapply [addirional clarification needed]

From: Peter Dalgaard <p.dalgaard_at_biostat.ku.dk>
Date: Sat, 22 Nov 2008 11:14:55 +0100

megh wrote:
> I need one more clarification here :
>
> Here I did :
>
> fn <- function(i) return(list(i, i^2))
> ss = sapply(1:4, fn)
>
> Here the object "ss" should be a matrix object :
> is.matrix(ss)
>
> However I feel it lacks some the matrix object properties. For example the
> syntax "min(ss[1,])" generates an error :
> "Error in min(ss[1, ]) : invalid 'type' (list) of argument".
>
> What should be the way out? Am I missing something ?

ss is a dim'ed list object, because fn returns a list. This appears to be a feature, although rarely used. One point is that you can do

 > fn <- function(i) return(list(as.character(i), i^2))
 > ss <- sapply(1:4, fn)
 > ss
      [,1] [,2] [,3] [,4]

[1,] "1" "2" "3" "4"
[2,] 1 4 9 16
 > ss[,1]
[[1]]
[1] "1"

[[2]]
[1] 1

I.e., the rows can be of different mode.

The easiest way out is just not to do that, i.e. return a vectore c(i, i^2) instead.

-- 
    O__  ---- Peter Dalgaard             Ă˜ster Farimagsgade 5, Entr.B
   c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
  (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard_at_biostat.ku.dk)              FAX: (+45) 35327907

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Sat 22 Nov 2008 - 10:17:53 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 22 Nov 2008 - 11:30:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive