rstringcbind

How to separate and reattach columns with dplyr


I was wondering on how to separate into two diffrent chunks of the dataframe, a big dataframa and then make the column binding in dplyr

I have use the following code

library(string)

new = cbind(mtcars[str_detect(mtcars$am, "0"),][1:13,],
            mtcars[str_detect(mtcars$am, "1"),][,9:11])

But I am looking for something different and more efficient to use in a wrapping code with dplyr, forr example.


Solution

  • Do you mean something like this?

    mtcars |>
      filter(am == 0) |>
      slice_head(n = 13) |>
      bind_col(
        filter(mtcars, am == 1)[, 9:11]
    )
    

    You can also use dplyr::select to select 9th to 11th columns.

    mtcars |> filter(am == 1) |> select(9:11)
    

    Honestly, base R is efficient enough in this case.