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

Sundar Dorai-Raj sundar.dorai-raj at PDF.COM
Wed Sep 1 17:55:22 CEST 2004



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 ???
> }
> 

You're better off using the data.frame names with the "[" operator and 
not the data.frame name itself with the "$" operator. How about:

val <- list()
for(i in 1:3) {
   ratCol <- paste("ratio", i, sep = "")
   ratio.i <- basin.param[, ratCol]
   crit <- ratio.i > 0
   val[[ratCol]] <- ratio.i[crit] + basin.param$val[crit]
}

--sundar




More information about the R-help mailing list