[R] coercing a string naming to a variable name and return value

Adaikalavan Ramasamy ramasamy at cancer.org.uk
Wed Sep 1 18:03:51 CEST 2004


I am not sure if I understand your problem but I think you might be
close to the solution. Perhaps if you changed 'index' in your code to
'i', you might get the answer. Try this :

set.seed(1066)
m <- matrix(rnorm(9), nc=3)
colnames(m) <- paste("ratio", 1:3, sep="")
 m
         ratio1     ratio2    ratio3
[1,] -0.5917632  0.2399853  2.810498
[2,]  0.2926060  0.9197199 -0.977170
[3,] -0.9212630 -0.7864827  1.746278


for(i in 1:3){ 
 name   <- paste("ratio", i, sep="")
 values <- m[ , name]
 cat("Column named", name, "has values", values, "\n") }
}

Column named ratio1 has values -0.5917632 0.2926060 -0.921263
Column named ratio2 has values 0.2399853 0.9197199 -0.7864827
Column named ratio3 has values 2.810498 -0.97717 1.746278


for(i in c(2,3,1)){ 
   cat("Column named", name <- paste("ratio", i, sep=""), 
       "has values", m[ , name], "\n") 
}
Column named ratio2 has values 0.2399853 0.9197199 -0.7864827
Column named ratio3 has values 2.810498 -0.97717 1.746278
Column named ratio1 has values -0.5917632 0.2926060 -0.921263



On Wed, 2004-09-01 at 16:41, Dewez Thomas wrote:
> Hi all,
> 
> I haven't been able to find how to assess a variable who's name is
> constructed with paste. The problem is following: In a data frame, there are
> 12 columns whose title vary only by a digit, all other part being equal. I
> would like to compute a operation on a subset these variables and parse them
> in turn.
> 
> the data frame "basin.param" contains columns called ratio1, ratio2,
> ratio3...
> in each of these ratios I want to retain only values above 0. This could be
> put like this
> 
> crit<- which(basin.param$ratio1 > 0)
> basin.param$ratio1[crit] + basin.param$val[crit]
> 
> OK, so what if I want to increment from ratio1 to ratio3 automatically and
> return the value of the variable represented by the string? (does this make
> sense?)
> # Create the variable name 
> for (i in 1:3){
> string.variable <- paste("basin.param$ratio", index, sep="")
> # What is the instruction to interpret the string.variable value ???
> }
> 
> Cheers
> 
> Thomas
> ***
> Le contenu de cet e-mail et de ses pièces jointes est destin...{{dropped}}
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list