2017-08-17 3 views
0

Wie finde ich die Anzahl der Vorkommen einer Liste von Wörtern? Ich kann für ein Wort suchen, wie folgt:Wie suche ich die Anzahl der Vorkommen einzelner Wörter in Textdaten?

dplyr::filter(data, grepl("apple", data$content,ignore.case = TRUE)) 
length(x$content) 

Der | Separator ermöglicht es mir, alle Vorkommen zusammenzufassen. Aber ich möchte jedes Wort einzeln zählen.

Die Worte könnte als eine Reihe in einer CSV oder geschrieben als ein Vektor in R selbst, beispielsweise geliefert werden:

words <- c("apple","orange","pear","pineapple") 

Ein Falten ist, dass die data$count eine Spalte von tweets sind so kann das Wort mehr auftreten als einmal pro Tweet. Daher möchte ich nur zählen, wenn sie in der Reihe auftreten.

+0

Siehe 'stringr :: str_count' – www

Antwort

1

Sie könnten logical Werte für das Vorhandensein/Nichtvorhandensein des Zielwörter wie diese:

library(tidyverse) 

words <- c("apple","orange","pear","pineapple") 

data <- tibble(content = c("Ony my grocery list are green apples, red apples and oranges", 
          "My favorite froyo flavors are pineapple, peach-pear and pear")) 

boundary_words <- paste0("\\b", words) # if you want to avoid counting the apple in pineapple 

map_dfc(boundary_words, ~ as.tibble(grepl(., data$content))) %>% 
    set_names(words) %>% 
    bind_cols(data, .) 

# A tibble: 2 x 5 
                 content apple orange pear pineapple 
                 <chr> <lgl> <lgl> <lgl>  <lgl> 
1 Ony my grocery list are green apples, red apples and oranges TRUE TRUE FALSE  FALSE 
2 My favorite froyo flavors are pineapple, peach-pear and pear FALSE FALSE TRUE  TRUE 
+0

Groß , Danke. Eine Erweiterung, die ich hinzufügte, war, das Objekt 'newdata' zu benennen und die Anzahl von 'TRUE's in der relevanten Spalte mit' apply (X = newdata [9:12], 2, FUN = Funktion (x) Länge (welche (x = = 'WAHR'))) ' –

0

Mit dem stringr Paket ...

library(stringr) 
words <- c("apple","orange","pear","pineapple") 

data <- c("On my grocery list are green apples, red apples and oranges", 
      "Oranges are my favourite, but I also like pineapples and pearls") 

sapply(words,function(w) 
     str_count(str_to_lower(str_split(data," ")), #split into words and set to lower case 
       paste0("\\b",w,"s*\\b"))) #adds word boundaries and optional plural -s 

    apple orange pear pineapple 
[1,]  2  1 0   0 
[2,]  0  1 0   1 

This allows for capital letters, and should only count whole words (perhaps with an -s plural). 
Verwandte Themen