[R] Indexing variables within lapply?
Uwe Ligges
ligges at statistik.uni-dortmund.de
Tue Nov 29 13:41:54 CET 2005
Christian Bieli wrote:
> Hello
> I am using R 2.2.0 with Windows XP.
> I've got a five element list object, each element containing two
> dataframes of equivalent size.
>
> > str(mylist)
> List of 1
> $ data1:List of 2
> ..$ data1a :`data.frame': 77 obs. of 63 variables:
> .. ..$ var1 : num [1:77] 0.41375 0.00056 1.43040 1.43528 0.61730 ...
> .. ..$ var2 : num [1:77] 1.154 1.686 0.673 0.800 0.760 ...
> .. ..$ var3 : num [1:77] 1.245 0.575 0.934 0.461 0.757 ...
> .
> .
> .
> ..$ data1b :`data.frame': 77 obs. of 63 variables:
> .. ..$ var1 : num [1:77] 1284.59 7.59 1.16 8.66 2646.38 ...
> .. ..$ var2 : num [1:77] 1.231 1.129 0.427 1.132 0.692 ...
> .. ..$ var3 : num [1:77] 1.36 0.68 1.39 2.54 1.39 ...
> .
> .
> .
> $ data2:List of 2
> ..$ data2a :`data.frame': 77 obs. of 63 variables:
> .. ..$ var1 : num [1:77] 0.41375 0.00056 1.43040 1.43528 0.61730 ...
> .. ..$ var2 : num [1:77] 1.154 1.686 0.673 0.800 0.760 ...
> .. ..$ var3 : num [1:77] 1.245 0.575 0.934 0.461 0.757 ...
> .
> .
> .
> ..$ data2b :`data.frame': 77 obs. of 63 variables:
> .. ..$ var1 : num [1:77] 1284.59 7.59 1.16 8.66 2646.38 ...
> .. ..$ var2 : num [1:77] 1.231 1.129 0.427 1.132 0.692 ...
> .. ..$ var3 : num [1:77] 1.36 0.68 1.39 2.54 1.39 ...
> .
> .
> .
>
> My goal is to do calculations with corresponding variables (e.g.
> correlation between var1 of data1a and var1 of data1b) within each list
> element.
> I tried to do it with lapply(data, myfunction,...), but I dont know if
Without having tested:
myfunction <- function(x, var){
cor(x[[1]][[var]], x[[2]][[var]])
}
lapply(data, myfunction, var="var1")
Uwe Ligges
> theres a way to index the two vars within lapply.
> There is certainly a way to do it by looping, but lapply is much more
> elegant.
>
> Thank you for your help.
> Christian
>
More information about the R-help
mailing list