[R] Error with lapply [addirional clarification needed]
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Sat Nov 22 11:14:55 CET 2008
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
More information about the R-help
mailing list