返回每个数据帧行的Twitter句柄

问题描述 投票:0回答:2

给出以下数据帧:

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))    
    }
})

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

r twitter stringr rtweet
2个回答
1
投票
library(tidyverse)

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

输出:

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

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
© www.soinside.com 2019 - 2024. All rights reserved.