Skip to content
Prev 398121 / 398506 Next

Extracting portions of one vector to create others

The solutions offered are fine but perhaps not quite directly what was asked for.

A careful reading seems to suggest they simply want a way to index the data.frame multiple ways by creating a set of vectors containing zero or one. He seems to want a solution for a specific case. This seems like it can be solved fairly easily with ifelse() as in:

CLASS1 <- ifelse(Beth$CLASS==1, 1, 0)
CLASS2 <- ifelse(Beth$CLASS==2, 1, 0)
CLASS4 <- ifelse(Beth$CLASS==4, 1, 0)
CLASS7 <- ifelse(Beth$CLASS==7, 1, 0)
CLASS9 <- ifelse(Beth$CLASS==9, 1, 0)

Of course a more general solution could consider arbitrary factors and create either custom names for resulting vectors or create a list of such vectors or other data structures like the matrix one being provided.

And, of course, sometimes you do not choose this way of having a "Boolean vector" to be used as an index but can use standard R (or packages like dplyr) to select the rows needed with a query.

-----Original Message-----
From: R-help <r-help-bounces at r-project.org> On Behalf Of Jeff Newmiller via R-help
Sent: Tuesday, September 2, 2025 4:16 AM
To: r-help at r-project.org
Subject: Re: [R] Extracting portions of one vector to create others

This is an extremely common transformation in regression, and it has a dedicated function (model.matrix) for accomplishing it in R. It does presume you have a bit of familiarity with the formula literal type in R... which is created using the tilde character (e.g. ~ CLASS). Also, since including an intercept term in a regression is the default, if you only want the columns you described then you need to inform the function that you want to leave the intercept out (~ CLASS - 1). It doesn't apply this discrete transformation unless the referenced variable is a factor variable, so I convert it from integer type in the short example below.

Beth <- data.frame(

  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))
Beth$CLASS <- as.character(Beth$CLASS)
result <- model.matrix( ~ CLASS - 1, Beth)
result

Note that the result is a matrix, not a data frame so you will have to use brackets and a blank for the row spec if you want to access one column at a time: 

result[, "CLASS1"]

Refer to the help page for more on this function:
?model.matrix
On September 1, 2025 7:09:56 AM PDT, Paul Zachos <paz at acase.org> wrote: