使用正则表达式填充数据框列(?)

时间:2016-06-04 02:58:51

标签: regex r dataframe

好的,我有一个网络论坛评论的数据框。每行都有一个包含ID的单元格,该ID是该评论的父评论链接的一部分。这些行包含注释的完整永久链接,其中ID是变化的部分。

我想添加一个列,显示附加到该父评论的用户名。我假设我需要使用一些正则表达式函数,在这一点上我觉得很神秘。

在工作流术语中,我需要找到其URL包含父注释ID的行,从该行中获取用户名。这是一个玩具示例:

toy <- rbind(c("yes?", "john", "www.website.com/4908", "3214", NA), c("don't think so", "mary", "www.website.com/3958", "4908", NA))
toy <- as.data.frame(toy)
colnames(toy) <- c("comment", "user", "URL", "parent", "parent_user")

         comment user                  URL parent parent_user
1           yes? john www.website.com/4908   3214        <NA>
2 don't think so mary www.website.com/3958   4908        <NA>

需要成为:

         comment user                  URL parent parent_user
1           yes? john www.website.com/4908   3214        <NA>
2 don't think so mary www.website.com/3958   4908        john

此列中的某些值将为NA,因为它们是顶级注释。等等,

dataframe$parent_user <- dataframe['the row where parent
ID i is found in the URL column', 'the user name column in that row']

谢谢!

3 个答案:

答案 0 :(得分:6)

另一种选择,使用基础R中的i函数,“删除所有路径,包括最后一个路径分隔符(如果有的话)

basename

答案 1 :(得分:4)

也许不是最漂亮的方式,但可以选择:

toy$parent_user <- sapply(toy$parent, 
                          function(x){p <- toy[x == sub('[^0-9]*', '', toy$URL), 'user'];
                                      ifelse(length(p) > 0, as.character(p), NA)})

toy
#          comment user                  URL parent parent_user
# 1           yes? john www.website.com/4908   3214        <NA>
# 2 don't think so mary www.website.com/3958   4908        john

第二行实际上只是处理缺乏匹配的案件。

答案 2 :(得分:4)

以下是包含stri_extractmatch

的矢量化选项
library(stringi)
toy$parent_user <- toy$user[match(toy$parent,stri_extract(toy$URL, 
            regex=paste(toy$parent, collapse="|")))]
toy
#         comment user                  URL parent parent_user
#1           yes? john www.website.com/4908   3214        <NA>
#2 don't think so mary www.website.com/3958   4908        john

或者正如@jazzurro所提到的,更快的选择是使用stri_extractdata.tablefmatch

library(data.table)
library(fastmatch)
setDT(toy)[, parent_user := user[fmatch(parent, 
                  stri_extract_last_regex(str=URL, pattern = "\\d+"))]]

base R选项

with(toy, user[match(parent, sub("\\D+", "", URL))])
#[1] <NA> john
#Levels: john mary

nchar('with(toy, user[match(parent, sub("\\D+", "", URL))])')
#[1] 51

nchar('toy$user[match(toy$parent, basename(as.character(toy$URL)))]')
#[1] 60
相关问题