Statistically Significant

December 13, 2009

R Trick (Nerd Alert)

Filed under: Math — Hoxie @ 11:38 am

At work this past week, I finally figured out how to do something in R that I’ve been wanting to do for a while now. The problem has to do with creating and assigning variables using a loop. I figured out how to do mass variable creation using a loop this summer: to assign a random value between 0 and 1 to variables z1, z2, …, z10 using a loop, you can use:
for (index in 1:10){
assign(paste(“z”, index, sep=”") , runif(1))
}
(I can’t think of a place I’d choose to do this over just creating a 10-element vector of random numbers using “z <- runif(10)” and accessing the elements of the vector as I needed them, but there are places where it’s helpful to create a few variables using the loop index.)

But what if you have variables z1, z2, …, z10 created already and you want to work with each of them separately? I didn’t know how to create a “current variable” inside of the loop. Trying something similar fails:
for (index in 1:10){
assign(“current_value” , paste(“z”, index, sep=”"))
cat(current_value, “\n”)
# do complicated stuff
}
This will print “z1″, “z2″, … “z10″ instead of the values contained in our ten z variables.

The solution I discovered this past week:
for (index in 1:10){
eval(parse(text=paste(“current_value <- z”, index, sep=”")))
cat(current_value, “\n”)
}
For index==1, for example, this prepares the string “current_value <- z1″ and then submits it to R for evaluation, so now the variable current_value contains the value of z1. Nice.

Leave a Reply