A subset with a drawing

Say I have a df data frame

df <- data.frame( a1 = 1:10, b1 = 2:11, c2 = 3:12 )

I want to multiply columns, but with a pattern

df1 <- subset( df, select= (pattern = "1") )

To obtain

> df1
   a1 b1
1   1  2
2   2  3
3   3  4
4   4  5
5   5  6
6   6  7
7   7  8
8   8  9
9   9 10
10 10 11

Is it possible?

+4
source share
1 answer

This can be done using

subset(df, select = grepl("1", names(df)))

To automate this, you can use functions as functions [to execute a subset. Pair that with one of the regex functions R, and you have everything you need.

As an example, this is a user-defined function that implements the ideas mentioned above.

Subset <- function(df, pattern) {
  ind <- grepl(pattern, names(df))
  df[, ind]
}

, .. grepl, , , pattern, [ . df :

> Subset(df, pattern = "1")
   a1 b1
1   1  2
2   2  3
3   3  4
4   4  5
5   5  6
6   6  7
7   7  8
8   8  9
9   9 10
10 10 11
+7

All Articles