在数据框中的几行上提取具有匹配模式的ID [英] Extract id with matching pattern on several rows in dataframe

查看:53
本文介绍了在数据框中的几行上提取具有匹配模式的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在处理的数据框的示例:

Here is an example of a dataframe I'm working on :

id  string
1    no
1    yes
1    yes
2    no
2    yes
3    yes
3    yes
3    no

我想提取id,其中最后两行的列string包含字符串"yes".

I want to extract the id for which the last two rows contain the string "yes" for the column string.

因此结果将是:

id   string
 1    yes
 1    yes

我只有一个id,即1.

我尝试使用for循环来执行此操作,但是由于我有20万多行,因此循环花费了太多时间:超过5分钟.

I tried to do this with a for loop but since I have more than 200 000 lines, the loop is taking too much time : more than 5 minutes.

我尝试过这个:

vec_id <- unique(df$id)

for(id in vec_id){
   if( tail(df[which(df$id == id),"string"])[1] & tail(df[which(df$id == id),"string"])[2] ){
      vec_id <- append(vec_id, id) 
     }

是否有任何功能或方法可以更快地完成此任务?

Are there any functions or ways to do this task more fastly ?

推荐答案

我们可以使用data.table.将'data.frame'转换为'data.table'(setDT(df1)),按'id',if all分组,最后两个观察值中的'string'为'yes',然后得到最后两个'字符串"(使用tail).

We can use data.table. Convert the 'data.frame' to 'data.table' (setDT(df1)), grouped by 'id', if all the 'string' from the last two observations are 'yes' then get the last two 'string' (using tail).

library(data.table)
setDT(df1)[, if(all(tail(string,2)=="yes")) .(string = tail(string,2)) , id]
#  id string
#1:  1    yes
#2:  1    yes

注意:data.table语法通常为data.table[i, j, by].

NOTE: The data.table syntax is often data.table[i, j, by].

这篇关于在数据框中的几行上提取具有匹配模式的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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