[英]How to assign a variable name in a loop in R
imagine I want to go through a loop and when I find the value that I am interested in, I want to use that value as a new variable name.想象一下,我想通过一个循环访问 go,当我找到我感兴趣的值时,我想将该值用作新变量名。 The code below can better describe what I mean.
下面的代码可以更好地描述我的意思。
Here I want the name Bob to be a new variable containing the character value "my_name".在这里,我希望名字 Bob 成为一个包含字符值“my_name”的新变量。 But this code that I have written does not do the job.
但是我编写的这段代码并不能完成这项工作。 I would greatly appreciate if someone points out where I make the mistake
如果有人指出我犯错的地方,我将不胜感激
names = c("Tom", "Bob", "Dan")
for (i in 1:length(names)){
name = names[i]
if (names[i] == "Bob"){
names[i] = "my_name"
print(Bob)
}
}
you can make use of "assign".您可以使用“分配”。
names = c("Tom", "Bob", "Dan")
for (i in 1:length(names)){
name = names[i]
if (names[i] == "Bob"){
assign(names[i],"my_name")
print(Bob)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.