通过列名的复杂模式的子集数据帧

时间:2013-10-05 13:46:47

标签: regex r grep

我有一个如下所示的数据集:

  • 两轮数据(.t0.t1
  • 多个尺度(thisthat
  • 每个比例的多个项目(12222a
  • 要忽略的几个变量(v2v3ignore.t0ignore.t1this.t0this.t1that.t0that.t1

dat <- data.frame(id = seq(from=1, to=10, by=1),
                  v2 = rnorm(10),
                  v3 = rnorm(10),
                  ignore.t0 = rnorm(10),
                  this.t0 = rnorm(10),
                  this1.t0 = rnorm(10),
                  this22.t0 = rnorm(10),
                  this22a.t0 = rnorm(10),
                  that.t0 = rnorm(10),
                  that1.t0 = rnorm(10),
                  that22.t0 = rnorm(10),
                  that22a.t0 = rnorm(10),
                  ignore.t1 = rnorm(10),
                  this.t1 = rnorm(10),
                  this1.t1 = rnorm(10),
                  this22.t1 = rnorm(10),
                  this22a.t1 = rnorm(10),
                  that.t1 = rnorm(10),
                  that1.t1 = rnorm(10),
                  that22.t1 = rnorm(10),
                  that22a.t1 = rnorm(10))

我希望将数据框的子集包含在id中,并且只包含以下列:

  • 比例名称(thisthat)AND
  • 句号前的数字(1.)或数字和字母(22a.

所以最后,数据框应如下所示:

dat2 <- data.frame(
                   id = seq(from=1, to=10, by=1),
                   #v2 = rnorm(10),
                   #v3 = rnorm(10),
                   #ignore.t0 = rnorm(10),
                   #this.t0 = rnorm(10),
                   this1.t0 = rnorm(10),
                   this22.t0 = rnorm(10),
                   this22a.t0 = rnorm(10),
                   #that.t0 = rnorm(10),
                   that1.t0 = rnorm(10),
                   that22.t0 = rnorm(10),
                   that22a.t0 = rnorm(10),
                   #ignore.t1 = rnorm(10),
                   #this.t1 = rnorm(10),
                   this1.t1 = rnorm(10),
                   this22.t1 = rnorm(10),
                   this22a.t1 = rnorm(10),
                   #that.t1 = rnorm(10),
                   that1.t1 = rnorm(10),
                   that22.t1 = rnorm(10),
                   that22a.t1 = rnorm(10))

数据框比这里表示的要大得多,因此无法输入列索引。也不可能只查找比例名称,因为this.t0this.t1that.t0that.t1会被捕获。

# not quite right
dat2$id <- dat$id
scales <- c("this", "that")
keep.index <- grep(paste(scales,collapse="|"), names(dat))
temp <- dat[keep.index]
dat2 <- cbind(dat2, temp)

如何修改grep模式以在句点之前查找数字OR(数字和字符)?或者是否有更好的方法?

1 个答案:

答案 0 :(得分:6)

这适用于您的示例:

dat[c("id", grep("(this|that)\\d+[a-z]?\\.", names(dat), value = TRUE))]

其中:

  1. \\d+代表一个或多个数字
  2. [a-z]?适用于零个或一个小写字母
  3. \\.用于点
  4. 如果要为各种scales动态构建模式,可以执行以下操作:

    scales <- c("this", "that")
    pattern <- sprintf("(%s)\\d+[a-z]?\\.", paste(scales, collapse = "|"))
    dat[c("id", grep(pattern, names(dat), value = TRUE))]