示例数据
A<-c(1,4,5,6) B<-c(4,6,7,8) C<-c(6,9,1,2) D<-c(5,6,7,3) E<-c(10,11,12,19) DF<-data.frame(A,B,C,D,E) colnames(DF)<-c("A_1","B_1","C_2","D_2","TEST") One<-1 Two<-2我想使用grep根据最后一列中的条件删除(生成NA)我的数据。
DF[DF$TEST>15,grep(Two,colnames(DF))]<-NA工作得很好
DF[DF$TEST>15,grep(Two|One,colnames(DF))]<-NA才不是
以防数值数据略有不同
DF[DF$TEST>15,grep(2,colnames(DF))]<-NA这很好用
DF[DF$TEST>15,grep(2|1,colnames(DF))]<-NA这没有
理想情况下,我希望能够使用grep根据几个每个定义的变量删除数据:
grep(One|Two|Three|Four)或者如果处理数字
grep(1:4)而且我不确定我是否可以在正则表达式中添加添加内容,但最终如果我能做到这一点最简单:
DF[DF$TEST>15,grep(One+1,colnames(DF))]<-NA #If I were trying to grep on 2要么
DF[DF$TEST>15,grep(One+1:One,colnames(DF))]<-NA #If I were trying to grep on 1:2Example Data
A<-c(1,4,5,6) B<-c(4,6,7,8) C<-c(6,9,1,2) D<-c(5,6,7,3) E<-c(10,11,12,19) DF<-data.frame(A,B,C,D,E) colnames(DF)<-c("A_1","B_1","C_2","D_2","TEST") One<-1 Two<-2I want to use grep to drop (make NA) my data based on conditions found in the last column.
DF[DF$TEST>15,grep(Two,colnames(DF))]<-NAWorks just fine
DF[DF$TEST>15,grep(Two|One,colnames(DF))]<-NADoes Not
And just in case numerical data is slightly different
DF[DF$TEST>15,grep(2,colnames(DF))]<-NAThis works fine
DF[DF$TEST>15,grep(2|1,colnames(DF))]<-NAThis does not
Ideally I would like to be able to use grep to drop data based on several per-defined variables:
grep(One|Two|Three|Four)or if dealing with numbers
grep(1:4)And I'm not sure if I can get away with addition in my regular expressions, but ultimately it would be easiest if I could do this:
DF[DF$TEST>15,grep(One+1,colnames(DF))]<-NA #If I were trying to grep on 2or
DF[DF$TEST>15,grep(One+1:One,colnames(DF))]<-NA #If I were trying to grep on 1:2最满意答案
您需要从变量名称创建正则表达式模式。
就像是
or <- function(...) paste0('(', paste(..., sep = '|'), ')') or(One,Two) ## [1] '(1|2)' grep(or(One,Two), colnames(DF))You need to create a regex pattern from the variable names.
Something like
or <- function(...) paste0('(', paste(..., sep = '|'), ')') or(One,Two) ## [1] '(1|2)' grep(or(One,Two), colnames(DF))更多推荐
发布评论