Possible Duplicate:
R: How to convert string to variable name?
In R, I'm writing a for-loop that will iteratively create variable names and then assign values to each variable.
Here is a simplified version. The intention is to create the variable's name based on the value of iterating variable i, then fill the new variable with NA values.
(I'm only iterating 1:1 below since the problem occurs isn't related to the looping itself, but rather to the way the variable is being created and assigned.)
for (i in 1:1) {
#name variable i "Variablei"
varName = paste("Variable", as.character(i), sep="")
#fill variable with NA values
varName = rep(NA, 12)
print(varName)
print(Variable1)
}
Now, varName prints out as
[1] NA NA NA NA NA NA NA NA NA NA NA NA
and Variable1 is not found.
I understand on some level why this is buggy. In the first line, varName becomes a vector whose only entry is the string "Variable1". Then varName gets reassigned to hold the NA values. So when I try to print Variable1, it doesn't exist.
I think the more general issue is assignment vs. equality. In the first line, I want varName to be equal to the newly made string, but in the next line, I want varName to be assigned to the NA value vector.
What is the simplest way of creating that distinction? I'm also open to entirely different, better ways to go about this.
EDIT: Changed title because I had mischaracterized the problem.