[R] Use a variable of a list in a loop
Steve Lianoglou
mailinglist.honeypot at gmail.com
Thu Apr 8 01:11:30 CEST 2010
Hi,
On Wed, Apr 7, 2010 at 6:27 PM, rusers.sh <rusers.sh at gmail.com> wrote:
> Hi all,
> My problem may be related with the list manipulations. See below.
> #example data
> a<-list()
> a[[1]]<-data.frame(matrix(c(1:4),ncol=2));
> a[[2]]<-data.frame(matrix(c(5:8),ncol=2))
> I can use a[[1]]$X1,a[[1]]$X2,a[[2]]$X1,a[[2]]$X2 to use the corresponding
> variables. But what i need to do is to use function parameters to specify
> the variable names. The variable names will be different for various
> dataset, so i need a common place to indicate it.
> Something like,
> b<-function(var1=X1,var2=X2) {
> for (n in 1:2) {
> paste("a", "[[",n, "]]","$","var1", sep="")
> paste("a", "[[",n, "]]","$","var2", sep="")
> }
> }
> b(var1=X1,var2=X2) will have the same effect
> as a[[1]]$X1,a[[1]]$X2,a[[2]]$X1,a[[2]]$X2. Unfortunately, it does not
> work.
> Anybody can give me some suggestions on this? Hope it is clear for this
> question.
I'm not really sure what you're trying to do, but if you just want to
select out certain columns of a data.frame by passing the name of the
column around in someway, pass its name as a string and select the
collumn using [[var]] instead of $var.
For instance, using your data.frame ``a``. Say I want to either pull
out 'X1', or 'X2', you could do:
R> some.column <- 'X1'
R> a[[1]][[some.column]]
So whatever you are trying to do in your b() function, maybe you would
change it like so:
b <- function(var1='X1', var2='X2') {
## notice 'X1' and 'X2' are in quote in mine
...
cat(a[[n]][[var1]], '\n')
}
Also -- your call to `paste` isn't doing what I think you think it's
doing (what do you want it to do?)
Does that get you closer to what you need?
-steve
--
Steve Lianoglou
Graduate Student: Computational Systems Biology
| Memorial Sloan-Kettering Cancer Center
| Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact
More information about the R-help
mailing list