subset data frame by complex pattern of column names

前端 未结 1 1519
我寻月下人不归
我寻月下人不归 2021-01-14 07:14

I have a dataset that looks like the following:

  • two rounds of data (.t0 and .t1)
  • multiple scales (this and
1条回答
  •  北恋
    北恋 (楼主)
    2021-01-14 07:56

    This works for your example:

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

    where:

    1. \\d+ is for one or more digits
    2. [a-z]? is for zero or one lowercase letter
    3. \\. is for the dot

    If you want to build a pattern dynamically for various scales, you can do:

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

    0 讨论(0)
提交回复
热议问题