慕姐8265434
试一试grepl您的名字data.frame。grepl将正则表达式与目标TRUE匹配,如果找到匹配项则返回,FALSE否则返回。该函数是矢量化的,因此您可以传递一个字符串向量来进行匹配,并且您将获得一个返回布尔值的向量。例# Datadf <- data.frame( ABC_1 = runif(3), ABC_2 = runif(3), XYZ_1 = runif(3), XYZ_2 = runif(3) )# ABC_1 ABC_2 XYZ_1 XYZ_2#1 0.3792645 0.3614199 0.9793573 0.7139381#2 0.1313246 0.9746691 0.7276705 0.0126057#3 0.7282680 0.6518444 0.9531389 0.9673290# Use grepldf[ , grepl( "ABC" , names( df ) ) ]# ABC_1 ABC_2#1 0.3792645 0.3614199#2 0.1313246 0.9746691#3 0.7282680 0.6518444# grepl returns logical vector like this which is what we use to subset columnsgrepl( "ABC" , names( df ) )#[1] TRUE TRUE FALSE FALSE为了回答第二部分,我将创建子集data.frame,然后创建一个向量来索引要保留的行(逻辑向量),如下所示:set.seed(1)df <- data.frame( ABC_1 = sample(0:1,3,repl = TRUE), ABC_2 = sample(0:1,3,repl = TRUE), XYZ_1 = sample(0:1,3,repl = TRUE), XYZ_2 = sample(0:1,3,repl = TRUE) )# We will want to discard the second row because 'all' ABC values are 0:# ABC_1 ABC_2 XYZ_1 XYZ_2#1 0 1 1 0#2 0 0 1 0#3 1 1 1 0df1 <- df[ , grepl( "ABC" , names( df ) ) ]ind <- apply( df1 , 1 , function(x) any( x > 0 ) )df1[ ind , ]# ABC_1 ABC_2#1 0 1#3 1 1