[R] row, col function but for a list (probably very easy question, cannot seem to find it though)

David Winsemius dwinsemius at comcast.net
Mon Mar 26 17:33:27 CEST 2012


On Mar 25, 2012, at 6:17 PM, MBoersma wrote:

> Hi guys,
>
> I'm quite new to R but quite enthousiastic. I'm trying to rewrite a  
> bit of
> code in order to make it faster, so instead of nesting for loops I'm  
> trying
> some apply functions.

It is an urban myth that using 'apply' functions will deliver better  
performance than 'for' loops. It may even worsen performance or create  
obstacles when it is improperly used with dataframes. Most of the  
benefits come from improving readability and maintainability.


> Since it's a combination of lists of matrices and
> other matrices, I would like to use lapply() on the list and still  
> be able
> to use the list index to index in the matrices.

The usual approach to that problem is to use sapply:

x <- list()
  x <- sapply(1:10, function(z) x[[z]] <- 1:z )

But that is really a for loop in disguise and whatever inefficiency  
existed in the function being applied will still limit performance.

>
> So, in "code format"-
> x <- list()
> for (i in 1:10){
>  x[[i]] <- c(1:i)
> }
>
> lapply(x,length)
>
> is there a possible way to say "lapply(x, function(x) length(x)/ 
> index(x) )"
> and return 1's.

If you are working on an object named x then you should not be using x  
as an index:

  lapply(seq_along(x), function(z) length(x[[z]])/z )


> I would be looking for the index. I know that row() and
> col() work in the matrix case. I would find it interesting to use it  
> with
> arrays as well.

Terminology alert: You were not demonstrating any array objects.  
Arrays are not lists in R. Arrays, like matrices and dataframes, but  
unlike lists are dimensioned  (in the sense that the dim() function  
will retun a value. For the problem you posed, a list would be the  
natural results because it doesn't have a rectangular form. In R a  
list has a length but it doesn't have a dimension.

 > dim(x)
NULL


--
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list