如何在循环遍历数字序列时在赋值运算符两侧使用 paste0?

huangapple go评论66阅读模式
英文:

How to use paste0 on both sides of an assignment operator within a loop across a sequence of numbers?

问题

我有一个包含不同城市名称的字符向量。

names <- c("Tokyo","Bangkok")


我想要将每个城市名称存储在单独的字符向量中,可以通过以下方式实现:

name_1 <- names[1]
name_2 <- names[2]


但是,我更想使用循环,尝试了以下方式:

for (i in 1:2) {
assign(paste0("name_", i), names[i])
}


这会给我一个错误消息:

Error in assign(paste0("name_", i), names[i]) :
target of assignment expands to non-language object


如何解决这个问题?在我的真实数据中,我有数百个城市名称,所以我想使用循环或任何其他节省我为每个城市名称编写新代码行的技术。
英文:

I have a character vector that contains the names of different cities.

names &lt;- c(&quot;Tokyo&quot;,&quot;Bangkok&quot;)

I would like to store each city name in a separate character vector, which I could do by:

name_1 &lt;- names[1]
name_2 &lt;- names[2]

However, I would rather like to use a loop, which I tried by:

for (i in 1:2) {
  paste0(&quot;name_&quot;,i) &lt;- paste0(&quot;names[&quot;,i,&quot;]&quot;)
}

This gives me an error message:

Error in paste0(&quot;name_&quot;, i) &lt;- paste0(&quot;names[&quot;, i, &quot;]&quot;) : 
  target of assignment expands to non-language object

How can I solve this problem? In my real data, I have hundreds of city names, which is why I want to use a loop or any other technique that saves me from writing a new line of code for every city name.

答案1

得分: 2

paste0 在这里是一个误导,不需要出现在 RHS 上。assign 函数允许将变量分配为字符字符串:

for (i in 1:2) {
  assign(paste0("name_", i), names[i])
}

一般情况下不建议这样做。在这种特定情况下,可以简单地通过 names[i] 而不是 names_i 来引用相同的值,但你的用例可能不同。

英文:

paste0 is a red herring here; it's not needed on the RHS. The function assign allows assignment to a variable as a character string:

for (i in 1:2) {
  assign(paste0(&quot;name_&quot;, i), names[i])
}

This is not in general recommended. In this particular case, one can refer to the same value simply by names[i] as opposed to names_i, but your use-case may be different.

答案2

得分: 2

除了循环,您还可以将向量转换为具有名称的列表,然后使用 list2env()

names <- c("Tokyo", "Bangkok")

list2env(setNames(as.list(names), paste0("name_", seq_along(names))), .GlobalEnv)

name_1
# [1] "Tokyo"

name_2
# [1] "Bangkok"
英文:

Apart from a loop, you can also convert the vecter to a named list and then list2env().

names &lt;- c(&quot;Tokyo&quot;, &quot;Bangkok&quot;)

list2env(setNames(as.list(names), paste0(&quot;name_&quot;, seq_along(names))), .GlobalEnv)

name_1
# [1] &quot;Tokyo&quot;

name_2
# [1] &quot;Bangkok&quot;

huangapple
  • 本文由 发表于 2023年6月6日 13:13:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76411601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定