首页 > 解决方案 > 在特定列中与 grepl 匹配的模式后过滤行

问题描述

我有一个数据集(名为desktop),其中包含来自网络跟踪器的按时间顺序排列的信息,其中包含一列中不同用户访问的 URL 和另一列中的用户 ID。以搜索引擎分析为目标,我试图过滤所有包含用户向谷歌提交搜索查询的 URL 的行,我可以使用以下代码行:

data_google <- dplyr::filter(desktop, grepl('\\bgoogle.com/search\\b', desktop$url, ignore.case = T))

这工作正常。但是,我不仅对包含搜索查询的 URL 感兴趣,而且对用户在提交查询后访问的网页感兴趣。换句话说,用户实际点击的来自谷歌结果页面的链接。

是否不仅可以过滤 url 与模式匹配的行,还可以过滤该行之后的行?

任何帮助将不胜感激,谢谢

标签: rfilterdplyrgrepl

解决方案


你说信息是按时间顺序排列的,所以这样做的方法是简单地为用户的每次搜索提取下一条记录。下面的代码就是这样做的

#assign proper row index column
desktop$row_index <- 1:nrow(desktop) 
data_google <- dplyr::filter(desktop, grepl('\\bgoogle.com/search\\b', desktop$url, ignore.case = T))

data_google 中的行对应于 google 搜索 url。要获取用户访问的 url(可能是 google 搜索中的结果),您基本上会从桌面中获取该搜索 url 之后但在下一个搜索 url 之前具有最小 row_index 的行。

names(data_google) <- c("search_url","user_id","search_row_index")
temp <- merge(desktop, data_google, by = "user_id")
temp <- temp[order(temp$user_id),]
#from temp, remove the rows with search_row_index >= row_index, since we are interested in url AFTER the search
temp <- temp[which(! temp$search_row_index >= temp$row_index),]
#now for each user and search_row_index, simply take the row with minimum row_index, 
#that would be the very next url visited after each of the search by the user
right_after_search_data <- as.data.frame(temp %>% 
                                         group_by(user_id,search_row_index) %>% 
                                         filter(row_index==min(row_index)))

推荐阅读