使用正则表达式的 R 子集数据集 [英] R Subset Dataset Using Regular Expression

查看:66
本文介绍了使用正则表达式的 R 子集数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让下面的 R 代码运行得更快(即矢量化以避免使用 for 循环)?

Is there a way to make the R code below run quicker (i.e. vectorized to avoid use of for loops)?

我的示例包含两个数据框.首先是维度 n1*p.p 列之一包含名称.第二个数据框是一个列向量 (n2*1).它还包含名称.我想保留第一个数据帧的所有行,其中第二个数据帧的列向量中名称的某些部分出现在相应的第一个数据帧中.对不起,粗暴的解释.

My example contains two data frames. First is dimension n1*p. One of the p columns contains names. Second data frame is a column vector (n2*1). It contains names as well. I want to keep all rows of the first data frame, where some part of the name in the column vector of the second data frame appears in the corresponding first data frame. Sorry for the brutal explanation.

示例(数据框 1):

x        y 
Doggy    1 
Hello    2 
Hi Dog   3 
Zebra    4 

示例(数据框 2)

z
Hello
Dog

所以在上面的例子中,我想保留第 1,2,3 行而不是第 4 行.因为Dog"出现在Doggy"和Hi Dog"中.而你好"出现在你好"中.排除第 4 行,因为在Zebra"中没有出现Hello"或Dog"的部分.

So in the above example I want to keep rows 1,2,3 but NOT 4. Since "Dog" appears in "Doggy" and "Hi Dog". And "Hello" appears in "Hello". Exclude row four since no part of "Hello" or "Dog" appears in "Zebra".

下面是我执行此操作的 R 代码...运行良好.但是,对于我的真正任务.数据框 1 有 100 万行,数据框 2 有 50 个要匹配的项目.所以运行很慢.任何有关如何加快速度的建议表示赞赏.

Below is my R code to do this...runs fine. However, for my real task. Data frame 1 has 1 million rows and data frame 2 has 50 items to match on. So runs pretty slow. Any suggestion on how to speed this up are appreciated.

x <- c("Doggy", "Hello", "Hi Dog", "Zebra")
y <- 1:4
dat <- as.data.frame(cbind(x,y))
names(dat) <- c("x","y")

z <- as.data.frame(c("Hello", "Dog"))
names(z) <- c("z")

dat$flag <- NA
for(j in 1:length(z$z)){
for(i in 1:dim(dat)[1]){ 

    if ( is.na(dat$flag[i])==TRUE ) {
        dat$flag[i] <- length(grep(paste(z[j,1]), dat[i,1], perl=TRUE, value=TRUE))
    } else {

    if (dat$flag[i]==0) {
        dat$flag[i] <- length(grep(paste(z[j,1]), dat[i,1], perl=TRUE, value=TRUE))

    } else { 

    if (dat$flag[i]==1) {
        dat$flag[i]==1
    }
    }
    }
}
}

dat1 <- subset(dat, flag==1)
dat1  

推荐答案

试试这个:

dat[grep(paste(z$z, collapse = "|"), dat$x), ]

subset(dat, grepl(paste(z$z, collapse = "|"), x))

这篇关于使用正则表达式的 R 子集数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆