[R] apply in apply

From: baptiste Auguié <ba208_at_exeter.ac.uk>
Date: Fri, 30 May 2008 09:13:14 +0100

Dear list,

I need to apply a function on each column of each matrix contained in a list. Consider the following code,

> x <- 1:3
> my.data <- list(matrix(c(1,2,3,4,5,6),ncol=2),
> matrix(c(4,5,6,7,8,9),ncol=2))
> par(mfrow=c(2,2))
> results <- sapply(1:length(my.data),
> function(ii) apply(my.data[[ii]], 2, function(y) plot(x,y) )) #

> plot is for demonstration purposes

It works, but I think this is quite dirty code. Is there a simpler way of achieving this? I was considering recasting the list into a matrix, apply the function to all its columns, and then reshape the result into an array of adequate dimensions, as in:

> results <- sapply(matrix(unlist(my.data),ncol= 2 * length
> (my.data)), function(y) plot(x,y))
> #results <- matrix(results, ncol = length(my.data)) # when the
> actual function is used instead of plot

but again it feels a bit twisted.

Best regards,


Baptiste Auguié

Physics Department
University of Exeter
Stocker Road,
Exeter, Devon,

Phone: +44 1392 264187


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 Fri 30 May 2008 - 08:20:01 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 Sun 01 Jun 2008 - 23:33:49 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