Variable assignment within a for-loop [duplicate]

亡梦爱人 提交于 2019-12-18 12:42:41

问题


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.


回答1:


Assignment works like this:

<varname> = <expression>

or more traditionally

<varname> <- <expression>

So, in your code, you have only ever assigned to varName. It's not about assignment vs equality, just assignment. You may want to look at assign:

for (i in 1:5) {
  assign(paste0("Variable", i), 10*i)
} 

as a toy example.

Moreover, as noted in the comments, there are probably better approaches for your application. For example, why not just use a vector myvector and instead of having variables called Variable1, Variable2, etc you can refer to myvector[1], myvector[2] etc.

As an example, let us say you had planned to work with

Variable1 <- 'foo'
Variable2 <- 'bar'
Variable3 <- 'baz'

then, you could change you approach, and set

mydata <- c('foo', 'bar', 'baz')

and where you would previously have used Variable2 (which contains 'bar') you instead use mydata[2] (which also contains 'bar'). The point here is that it is much easier to work with vectors and dataframes in R than a long list of variables.

You could go further and name the entries:

names(mydata) <- paste0("V", 1:3)

which then allows you to write mydata["V2"] to retrieve bar.



来源:https://stackoverflow.com/questions/13213845/variable-assignment-within-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!