Skip to content
Prev 398116 / 398506 Next

Extracting portions of one vector to create others

Hi Paul,

Here's a way that creates new vectors as elements of a list.

Beth <- list(
 CLASS = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
   7, 7, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 1
 )
)

classes <- unique(Beth$CLASS)

# Loop over `classes` to operate on a single `class` in each iteration
result <- lapply(classes, function(class) {
  # Create a vector with 1 if Beth$CLASS is in class, 0 if not
  as.numeric(Beth$CLASS == class)
})

names(result) <- paste0("CLASS", classes)

with the result:
$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 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 0 0 0 0 0
0
[83] 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 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 0 0 0 0 0
0
[83] 0 0 0 0 0 0 0 0 0 0 0 0 0 0

[list truncated ...]

Regards,
Jeff
On Tue, Sep 2, 2025 at 2:44?PM Paul Zachos <paz at acase.org> wrote: