Re: [R] indexing list elements with lapply?

From: Jorge Ivan Velez <jorgeivanvelez_at_gmail.com>
Date: Fri, 22 Apr 2011 18:02:29 -0400

Dear Simon,

Try any of the following:

sapply(r, function(l) l[,2] / l[1, 2])
lapply(r, function(l) l[,2] / l[1, 2])

HTH,
Jorge

On Fri, Apr 22, 2011 at 5:52 PM, Simon Kiss <> wrote:

> Dear colleagues,
> I have a list that looks like what the code below produces. I need a
> function to go through each list element and work on the second column of
> each list element (the first column is irrelevant to me...if the proposed
> function works on the first column as a consequence of a writing something
> simple, that's fine).
> I need to index the second column of each list element to the first item in
> each column. So for each list, I need to divide each number in the second
> column by the first number in that column.
>
> This code does what I want, but it only works on one item in the list
> r[[1]][,2] / r[[1]][1,2].
>
> I've tried working with this function but can't get it to work:
> f<-function(x) {
> for (i in 1:5)
> {
>
> x[[i]][,2]/x[[i]][1,2]
> }
> }
>
> lapply(r, f)
>
> But I get this error message:
> Error in x[[i]][, 2] : incorrect number of dimensions
>
> Hope someone can help. I'm grateful for any suggestions.
> Yours, Simon Kiss
>
> ******dataset
>
> ff<-runif(10, 0.85, 1)
> ff<-cbind(ff, 1-ff)
> gg<-runif(10, 0.85, 1)
> gg<-cbind(gg, 1-ff)
> hh<-runif(10, 0.86, 1)
> hh<-cbind(hh, 1-hh)
> ii<-runif(10, 0.92, 1)
> ii<-cbind(ii, 1-ii)
> jj<-runif(10,0.76, 1)
> jj<-cbind(jj, 1-jj)
> r<-list(ff, gg, hh,ii, jj)
> *********************************
> Simon J. Kiss, PhD
> Assistant Professor, Wilfrid Laurier University
> 73 George Street
> Brantford, Ontario, Canada
> N3T 2C9
> Cell: +1 519 761 7606
>
> ______________________________________________
> 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.
>

        [[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. Received on Fri 22 Apr 2011 - 22:06:38 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 Sat 23 Apr 2011 - 00:30:32 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