简体   繁体   中英

Naming objects from functions

I am a beginner in 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:

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 :

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:

for (i in seq_along(a)) {
  assign(sub("\\d+$", "", a[i]), b[[i]])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM