Background: Try to automate some process within a custom function. For this I need to know:
How can I assign each element in a vector to a new single named element:
x <- c(19L, 8L, 9L, 18L)
[1] 19 8 9 18
desired_output:
n1 <- 19
n2 <- 8
n3 <- 9
n4 <- 18
> n1
[1] 19
> n2
[1] 8
> n3
[1] 9
> n4
[1] 18
I have tried:
z <- setNames(x, paste0("n", 1:length(x)))
n1 n2 n3 n4
19 8 9 18
CodePudding user response:
Maybe first turn the vector into a list, then use list2env
.
list2env(setNames(sapply(x, list), paste0("n", seq_along(x))), .GlobalEnv)