[英]Naming objects from functions
I am a beginner in R.我是 R 的初学者。 I have a vast data set and I am trying to create a loop to optimize the time.
我有一个庞大的数据集,我正在尝试创建一个循环来优化时间。
I have something like:我有类似的东西:
a <- c ('exam12', 'example22', 'e33')
b <- list (c (2,4,5,6), c (10,4,8,6), c (25, 3, 7, 30))
And I would like to use the strings of a
as the name of objects for other values, obtaining, in my environment, something like:我想使用
a
的字符串作为其他值的对象名称,在我的环境中获得类似:
exam <- c (2,4,5,6)
example <- c (10,4,8,6)
e <- c (25, 3, 7, 30)
I tried the following:我尝试了以下方法:
for (i in seq_along (a)) {
for (j in seq_along (b)) {
str_sub (a [i], start = 1, end = -1) <- b [j]
}
}
But I was not successful.但我没有成功。 I appreciate any help.
我很感激任何帮助。
You can use list2env
:您可以使用
list2env
:
a <- c ('exam12', 'example22', 'e33')
b <- list (c (2,4,5,6), c (10,4,8,6), c (25, 3, 7, 30))
a
# [1] "exam12" "example22" "e33"
b
# [[1]]
# [1] 2 4 5 6
#
# [[2]]
# [1] 10 4 8 6
#
# [[3]]
# [1] 25 3 7 30
ls()
# [1] "a" "b"
list2env(setNames(b, sub("\\d+$", "", a)), .GlobalEnv)
# <environment: R_GlobalEnv>
ls()
# [1] "a" "b" "e" "exam" "example"
exam
# [1] 2 4 5 6
For reference, you could also do this with assign
, for example:作为参考,您也可以使用
assign
执行此操作,例如:
for (i in seq_along(a)) {
assign(sub("\\d+$", "", a[i]), b[[i]])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.