Selection with dplyr on parameters in column names

I have a data table with lots of columns that look like this:

sd1_scale1 sd1_scale2 sd1_scale3 ... sd2_scale1 sd2_scale2 ... so on

I manipulate this data with dplyr and use select as follows:

select(code_group, sd1_scale1:sd1_scale13) 

I want to write a function that takes a number (sd number) and allocates columns, something similar to this:

  makeData <- function(sdNumber) { return select(code_group, sd{sdNumber}_scale1:sd{sdNumber}_scale13) } 

Is it possible to do with dplyr? I was unable to go into individual column indexes, so I have no idea how to do this. Thanks in advance!

+5
source share
1 answer

You can use select_ , as Gregor suggested, but you don't need to.

 library(dplyr) x <- read.csv(text = "sd1_scale1,sd1_scale2,sd1_scale3,sd2_scale1,sd2_scale2,sd2_scale3 1,2,3,4", header = TRUE) makeData1 <- function(x, sdNumber) { # Using `one_of` as explained in ?select select(x, one_of(paste0("sd", sdNumber, "_scale", 1:2))) } makeData2 <- function(x, sdNumber) { # Same effect using nonstandard evaluation, see vignette("nse") select_(x, .dots = paste0("sd", sdNumber, "_scale", 1:2)) } x %>% makeData1(2) x %>% makeData2(2) # same result 

I got it from that meaning

+11
source

Source: https://habr.com/ru/post/1210503/


All Articles