每个数据框行返回Twitter句柄

时间:2019-02-25 18:33:29

标签: r twitter stringr rtweet

给出以下数据框:

df <- as.data.frame(c("Testing @cspenn @test @hi","this is a tweet","this is a tweet with @mention of @twitter"))
names(df)[1] <- "content"

我正在尝试提取每行的单个twitter句柄,而不是一次提取所有

this example中,我具有此功能,可以将它们全部吐出来,但是我需要它们保持包含在每一行中。

df$handles <- plyr::ddply(df, c("content"), function(x){
    mention <- unlist(stringr::str_extract_all(x$content, "@\\w+"))
    # some tweets do not contain mentions, making this necessary:
    if (length(mention) > 0){
        return(data.frame(mention = mention))
    } else {
        return(data.frame(mention = NA))    
    }
})

如何仅按行提取句柄,而不是一次提取所有句柄?

2 个答案:

答案 0 :(得分:2)

您可以这样做。

xy <- stringr::str_extract_all(df$content, "@\\w+")
xy <- sapply(xy, FUN = paste, collapse = ", ")  # have all names concatenated
cbind(df, xy)

                                    content                  xy
1                 Testing @cspenn @test @hi @cspenn, @test, @hi
2                           this is a tweet                    
3 this is a tweet with @mention of @twitter  @mention, @twitter

答案 1 :(得分:1)

Declare @data DocumentObjectType
Select top 1 @data = DocumentObject from DocumentObject 

SELECT CAST(CONVERT(VARBINARY(MAX), @data,2) AS NVARCHAR(MAX));

输出:

library(tidyverse)

df %>%
  mutate(mentions = str_extract_all(content, "@\\w+"))