Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

r - subset with pattern

Say I have a data frame df

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

I wish to subset the columns, but with a pattern

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

To get

> 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 this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is possible to do this via

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

For automating this as a function, one can use use [ to do the subsetting. Couple that with one of R's regular expression functions and you have all you need.

By way of an example, here is a custom function implementing the ideas I mentioned above.

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

Note this does not error checking etc and just relies upon grepl to return a logical vector indicating which columns match pattern, which is then passed to [ to subset by columns. Applied to your df this gives:

> 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...