R中的grep具有多个数字或定义的变量(grep in R with multiple numerical or defined variables)

编程入门 行业动态 更新时间:2024-10-17 11:22:58
R中的grep具有多个数字或定义的变量(grep in R with multiple numerical or defined variables)

示例数据

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:2

Example 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<-2

I 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))]<-NA

Works just fine

DF[DF$TEST>15,grep(Two|One,colnames(DF))]<-NA

Does Not

And just in case numerical data is slightly different

DF[DF$TEST>15,grep(2,colnames(DF))]<-NA

This works fine

DF[DF$TEST>15,grep(2|1,colnames(DF))]<-NA

This 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 2

or

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))

更多推荐

本文发布于:2023-07-16 13:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128948.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   变量   定义   数字   grep

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!