Variable assignment within a for-loop [duplicate]

末鹿安然 提交于 2019-11-30 07:45:11

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.

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