1

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
TarJae
  • 72,363
  • 6
  • 19
  • 66

2 Answers2

2

Maybe first turn the vector into a list, then use list2env.

list2env(setNames(sapply(x, list), paste0("n", seq_along(x))), .GlobalEnv)
benson23
  • 16,369
  • 9
  • 19
  • 38
2

Using %=% from collapse

library(collapse)
paste0('n', seq_along(x)) %=% x

-output

> n1
[1] 19
> n2
[1] 8
> n3
[1] 9
> n4
[1] 18
akrun
  • 874,273
  • 37
  • 540
  • 662