[R] indexing list elements with lapply?
Simon Kiss
sjkiss at gmail.com
Fri Apr 22 23:52:35 CEST 2011
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
More information about the R-help
mailing list