【问题标题】:Subset column names with specific string具有特定字符串的子集列名
【发布时间】:2017-03-25 08:19:24
【问题描述】:

我正在尝试根据以特定字符串开头的列名对数据框进行子集化。我有一些像 ABC_1 ABC_2 ABC_3 和一些像 ABC_XYZ_1、ABC_XYZ_2、ABC_XYZ_3 的列

如何对我的数据框进行子集化,使其仅包含 ABC_1、ABC_2、ABC_3 ...ABC_n 列而不包含 ABC_XYZ_1、ABC_XYZ_2...?

我试过这个选项

set.seed(1)
df <- data.frame( ABC_1 = sample(0:1,3,repl = TRUE),
            ABC_2 = sample(0:1,3,repl = TRUE),
            ABC_XYZ_1 = sample(0:1,3,repl = TRUE),
            ABC_XYZ_2 = sample(0:1,3,repl = TRUE) )


df1 <- df[ , grepl( "ABC" , names( df ) ) ]

ind <- apply( df1 , 1 , function(x) any( x > 0 ) )

df1[ ind , ]

但这给了我 ABC_1...ABC_n ...和 ​​ABC_XYZ_1...ABC_XYZ_n...的列名我对 ABC_XYZ_1 列不感兴趣,只有 ABC_1 的列...。任何建议都很重要赞赏。

【问题讨论】:

    标签: r regex subset grepl


    【解决方案1】:

    要指定“ABC_”后跟一个或多个数字(即\\d+[0-9]+),您可以使用

    df1 <- df[ , grepl("ABC_\\d+", names( df ), perl = TRUE ) ]
    # df1 <- df[ , grepl("ABC_[0-9]+", names( df ), perl = TRUE ) ] # another option
    

    要强制列名以“ABC_”开头,您可以将^ 添加到正则表达式中,以便仅当“ABC_\d+”出现在字符串的开头而不是出现在其中的任何位置时才匹配。

    df1 <- df[ , grepl("^ABC_\\d+", names( df ), perl = TRUE ) ]
    

    如果dplyr更符合你的喜好,你可以试试

    library(dplyr)
    select(df, matches("^ABC_\\d+"))
    

    【讨论】:

    • 甚至可能是 "^ABC_\\d+"
    【解决方案2】:

    另一个直接的解决方案是使用substr

    df1 <- df[,substr(names(df),5,7) != 'XYZ']
    

    【讨论】:

      猜你喜欢
      • 2011-05-13
      • 2021-12-05
      • 2010-09-15
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-30
      • 2020-08-22
      • 1970-01-01
      相关资源
      最近更新 更多