Dplyr: select columns by position in NSE

I am trying to create a function that will select columns in DF based on their position. I will always need the first column and then a subset of DF. I have 1 object for each subset I need to select.

So far I have tried the following:

position <- "1,28:31" DF %>% select_(.dots = position)

but I get the following error: Error in parse(text = x) : <text>:1:2: unexpected 'x'

It would seem that the problem is separating the comma at the column position.

Is there a workaround?

+5
source share
3 answers

You can simply use select with a numeric index vector:

 positions <- c(1,28:31) DF %>% select(positions) 
+10
source
  Select.by.pos <- function(pos, dt){ return(dt[, pos]) } 

The pos argument should not be a string, but a numbered vector :) dt is a dataframe

0
source

Using mtcars and:

  • add auto as my first column
  • select `c (auto, first column and any column containing 'a')
  • a subset of data where only the sums of numeric strings are greater than the average of all sums of these strings

mtcars %>% mutate(auto = row.names(.)) %>% select(auto, 1, contains('a')) %>% dplyr::filter(rowSums(.[-1]) > mean(rowSums(.[-1])))

  auto mpg drat am gear carb 1 Mazda RX4 21.0 3.90 1 4 4 2 Mazda RX4 Wag 21.0 3.90 1 4 4 3 Datsun 710 22.8 3.85 1 4 1 4 Merc 240D 24.4 3.69 0 4 2 5 Merc 230 22.8 3.92 0 4 2 6 Merc 280 19.2 3.92 0 4 4 7 Fiat 128 32.4 4.08 1 4 1 8 Honda Civic 30.4 4.93 1 4 2 9 Toyota Corolla 33.9 4.22 1 4 1 10 Fiat X1-9 27.3 4.08 1 4 1 11 Porsche 914-2 26.0 4.43 1 5 2 12 Lotus Europa 30.4 3.77 1 5 2 13 Ferrari Dino 19.7 3.62 1 5 6 14 Maserati Bora 15.0 3.54 1 5 8 15 Volvo 142E 21.4 4.11 1 4 2 
0
source

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


All Articles