Skip to content
Prev 398117 / 398513 Next

Extracting portions of one vector to create others

On 9/1/2025 3:09 PM, Paul Zachos wrote:
Hello,

Here is a way. This creates a matrix with the vectors you ask for.
But it doesn't create 5 different vectors, it keeps them in one object 
only, a matrix.



CLASS <-
   c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
     1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
     2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L,
     4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 7L, 7L,
     7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
     7L, 7L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 1L)
Beth <- data.frame(CLASS)

eq <- c(1, 2, 4, 7, 9)
res <- sapply(eq, \(x) as.integer(x == Beth$CLASS))
colnames(res) <- paste0("CLASS", eq)
head(res)
#>      CLASS1 CLASS2 CLASS4 CLASS7 CLASS9
#> [1,]      1      0      0      0      0
#> [2,]      1      0      0      0      0
#> [3,]      1      0      0      0      0
#> [4,]      1      0      0      0      0
#> [5,]      1      0      0      0      0
#> [6,]      1      0      0      0      0


If you really want 5 different objects in the global environment, you 
can use ?list2env.
This is not a good practice, you will have related, loose objects in the 
globalenv, making your code harder to debug. Keep it simple.


as.data.frame(res) |>
   list2env(envir = .GlobalEnv)
#> <environment: R_GlobalEnv>

CLASS1
#>  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0
#> [39] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0
#> [77] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
CLASS2
#>  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 
1 1 1 1 1 1
#> [39] 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0
#> [77] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0


Hope this helps,

Rui Barradas