Возвращение маркеров Twitter для каждой строки данных - PullRequest
0 голосов
/ 25 февраля 2019

Учитывая следующий фрейм данных:

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 для каждой строки, а не все сразу.

Из в этом примере , У меня есть эта функция, которая выплевывает их все, но мне нужно, чтобы они оставались содержащимися в каждой строке.

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 голосов
/ 25 февраля 2019

Вы можете сделать это так.

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
0 голосов
/ 25 февраля 2019
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
...