2017-08-01 1 views
1

Kontext: Ich möchte kumulative Summe Spalte zu meinem tibble namens words_uni hinzufügen. Ich benutzte Bibliothek (dplyr), Funktion muate. I mit R-Version 3.4.1 64-Bit arbeiten - Microsoft Windows 10 und RStudio Version 1.0.143Seltsam: Cumsum arbeitet nicht auf dplyr

> head(words_uni) 
# A tibble: 6 x 3 
# Groups: Type [6] 
Type Freq   per 
<chr> <int>  <dbl> 
1 the 937839 0.010725848 
2  i 918552 0.010505267 
3 to 788892 0.009022376 
4  a 615082 0.007034551 

Dann habe ich folgendes:

> words_uni1 = words_uni %>% 
         mutate(acum= cumsum(per)) 
> head(words_uni1) 
# A tibble: 6 x 4 
# Groups: Type [6] 
Type Freq   per  acum 
<chr> <int>  <dbl>  <dbl> 
1 the 937839 0.010725848 0.010725848 
2  i 918552 0.010505267 0.010505267 
3 to 788892 0.009022376 0.009022376 
4  a 615082 0.007034551 0.007034551 

Problem: Es ist nicht das, was ich dabei hatte erwartet, und ich kann nicht sehen warum.

Ich würde mich über Ihre Kommentare freuen. Danke im Voraus.

+1

Warum gruppieren Sie Ihren Datenrahmen? Es ist nach Typ gruppiert. –

+0

@ AndrewBrēza danke für deinen Kommentar. Ich habe nach einem vorherigen Befehl gruppiert, um die Häufigkeit pro Wort zu erhalten. Ich wusste jedoch nicht, dass diese Situation die Cumsum-Funktion beeinflusst. – Sergio

Antwort

4

Sie müssen das tibble zuvor nach Typ gruppiert haben. Dies führt dazu, dass Ihr Aufruf mutate nach Typ berechnet. Hier

ist einige reproduzierbaren Code:

require(readr) 
require(dplyr) 

x <- read_csv("type, freq, per 
the, 937839, 0.010725848 
i, 918552, 0.010505267 
to, 788892, 0.009022376 
a, 615082, 0.007034551") 


### ungrouped tibble, desired results 
x %>% mutate(acum = cumsum(per)) 

# A tibble: 4 x 4 
type freq   per  acum 
<chr> <int>  <dbl>  <dbl> 
1 the 937839 0.010725848 0.01072585 
2  i 918552 0.010505267 0.02123112 
3 to 788892 0.009022376 0.03025349 
4  a 615082 0.007034551 0.03728804 

### grouped tibble 
x %>% group_by(type) %>% mutate(acum = cumsum(per)) 

# A tibble: 4 x 4 
# Groups: type [4] 
type freq   per  acum 
<chr> <int>  <dbl>  <dbl> 
1 the 937839 0.010725848 0.010725848 
2  i 918552 0.010505267 0.010505267 
3 to 788892 0.009022376 0.009022376 
4  a 615082 0.007034551 0.007034551 

Sie müssen einfach Ihre Daten nicht gruppieren.

word_uni %>% ungroup() %>% mutate(acum = cumsum(per)) 

Sollte der Trick tun.

+0

Danke @Beau Ich wusste nicht, dass ich die Daten aufheben musste. Es funktioniert perfekt! – Sergio