Skip to content
Back to formatted view

Raw Message

Message-ID: <1362899002.41042.YahooMailNeo@web142603.mail.bf1.yahoo.com>
Date: 2013-03-10T07:03:22Z
From: arun
Subject: list + lapply insead of matrix + apply
In-Reply-To: <CAEjRLuRagVgk+y_O+r4yNdPzp=W+TMHfaznT+KGx4WUUQsAxzQ@mail.gmail.com>

Hi, 
For the first case:
lst2<-lapply(x.list, calcnorm2, x.list)
?lapply(lst2,function(x) do.call("c",x))
#[[1]]
#[1]? 0.00000 31.75257

#[[2]]
#[1] 31.75257? 0.00000
A.K.



For the second case:
?lst1<-as.list(data.frame(t(apply(x,1,calcnorm2.const,x)))) 
?names(lst1)<- NULL 
?lst1 
#[[1]] 
#[1] ?0.00000 31.75257 

#[[2]] 
#[1] 31.75257 ?0.00000 




A.K.  
----- Original Message -----
From: ishi soichi <soichi777 at gmail.com>
To: r-help <r-help at r-project.org>
Cc: 
Sent: Sunday, March 10, 2013 1:18 AM
Subject: Re: [R] list + lapply insead of matrix + apply

there is a typo.

lapply(x.list, calcnorm, x.list)

should be

lapply(x.list, calcnorm2, x.list)

sorry.




2013/3/10 ishi soichi <soichi777 at gmail.com>

> I need to develop a simple list manipulation. Although it seems easier to
> do it in matrix form, but I need it in list form.
>
> I have a matrix
>
> x <- matrix(c(12.1, 3.44, 0.1, 3, 12, 33.1, 1.1, 23), nrow=2)
>
> for list form example, the conversion is
>
> x.list <- lapply(seq_len(nrow(x)), function(i) x[i,])
>
>
> ### list version
> calcnorm=function(a, b){
>? ?  diff <- mapply("-", a, b)
>? ?  diff2 <- mapply("*", diff, diff)
>? ?  sqrt.diff <-sqrt(sum(diff2))
>? ?  return(sqrt.diff)
> }
> calcnorm2=function(a,X){
>? ?  lapply(X, calcnorm, a)
> }
> lapply(x.list, calcnorm, x.list)
>
> [[1]]
> [[1]][[1]]
> [1] 0
>
> [[1]][[2]]
> [1] 31.75257
>
>
> [[2]]
> [[2]][[1]]
> [1] 31.75257
>
> [[2]][[2]]
> [1] 0
>
>
> ### matrix version
> calcnorm.const=function(a,b){
>? ?  return(sqrt((a-b)%*%(a-b)))
> }
> calcnorm2.const=function(a,data){
>? ?  apply(data,1,calcnorm.const,a)
> }
> apply(x,1,calcnorm2.const,x)
>
>? ? ? ? ? [,1]? ?  [,2]
> [1,]? 0.00000 31.75257
> [2,] 31.75257? 0.00000
>
> Ideally, for later purposes, the list form of the output should be
> something like
>
> [[1]]
> [1,]? 0 31.75257
> [[2]]
> [2,] 31.75257? 0
>
> I am getting confused here. Could anyone help me out for the right output
> FORM?
>
> ishida
>

??? [[alternative HTML version deleted]]

______________________________________________
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.