英文:
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 <- c("Tokyo","Bangkok")
I would like to store each city name in a separate character vector, which I could do by:
name_1 <- names[1]
name_2 <- names[2]
However, I would rather like to use a loop, which I tried by:
for (i in 1:2) {
paste0("name_",i) <- paste0("names[",i,"]")
}
This gives me an error message:
Error in paste0("name_", i) <- paste0("names[", i, "]") :
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("name_", 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 <- c("Tokyo", "Bangkok")
list2env(setNames(as.list(names), paste0("name_", seq_along(names))), .GlobalEnv)
name_1
# [1] "Tokyo"
name_2
# [1] "Bangkok"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论