2016-04-15 22 views
0

Ich verwende dplyr zum Parsen einer Spalte mit Sätzen und Berechnen der Anzahl der Ngrams für jede. Hier ist ein Beispiel, das das Problem zeigt, auf das ich stoße.Verwenden von muate, um die Anzahl der Ngramme zu erhalten

Wie Sie sehen, erwartet ngram_cnt 3 und 4, aber es ergibt sich eine Spalte mit 3,3. Das Problem ist, dass der Code die Anzahl der Ngramme für den ersten Satz zurückgibt und den Rest ignoriert. Sie können versuchen, weitere Sätze hinzuzufügen, die den gleichen Effekt haben. Was mache ich falsch?

library(NLP) 
library(dplyr) 
library(stringr) 

phrases <- c("this is the first", "and then comes the second") 
df <- data.frame(phrase = phrases, id = c(1, 2)) 
df %>% mutate(ngram_cnt = length(ngrams(str_split(phrase, "\\s")[[1]], 2))) 

Wenn ich sage,

phrases <- c("this is the first", "and then comes the second", 
      "and the third which is even longer") 
df <- data.frame(phrase = phrases, id = c(1, 2, 3)) 
df %>% mutate(ngram_cnt = str_length(phrase)) 

dann bekomme ich die erwarteten Ergebnisse (nämlich die Länge eines jeden Satzes).

Antwort

2

das, weil in

ist
df %>% mutate(ngram_cnt = length(ngrams(str_split(phrase, "\\s")[[1]], 2))) 

die [[1]] nur die Spaltung auf dem ersten Satz wählen , die gleich ist:

length(ngrams(str_split(phrases, "\\s")[[1]], 2)) 
# [1] 3 

Und nach mutate3

phrases <- c("this is the first", "and then comes the second") 
df <- data.frame(phrase = phrases, id = c(1, 2)) 
library("dplyr") 
in jeder Reihe versetzt

Sie können gelten Ihre Berechnung für Zeile mit rowwise:

df %>% rowwise() %>% mutate(ngram_cnt = length(ngrams(str_split(phrase, "\\s")[[1]], n = 2))) 
# Source: local data frame [2 x 3] 
# Groups: <by row> 
# 
#      phrase id ngram_cnt 
#      (fctr) (dbl)  (int) 
# 1   this is the first  1   3 
# 2 and then comes the second  2   4 

Oder mit einem group_by wenn Ihre ID eindeutig ist:

df %>% group_by(id) %>% mutate(ngram_cnt = length(ngrams(str_split(phrase, "\\s")[[1]], n = 2))) 
# Source: local data frame [2 x 3] 
# Groups: id [2] 
# 
#      phrase id ngram_cnt 
#      (fctr) (dbl)  (int) 
# 1   this is the first  1   3 
# 2 and then comes the second  2   4 

Oder Sie können die Funktion vektorisiert, die die Länge von ngrams berechnen:

length_ngrams <- function(x) { 
    length(ngrams(str_split(x, "\\s")[[1]], n = 2)) 
} 
length_ngrams <- Vectorize(length_ngrams) 
df %>% mutate(ngram_cnt = length_ngrams(phrase)) 
#      phrase id ngram_cnt 
# 1   this is the first 1   3 
# 2 and then comes the second 2   4 
Verwandte Themen