Search code examples
rvectorassign

How to automate to split a vector in single element named scalars


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

Solution

  • Using %=% from collapse

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

    -output

    > n1
    [1] 19
    > n2
    [1] 8
    > n3
    [1] 9
    > n4
    [1] 18