1
votes

I am using summarise to perform a calculation for each row of my data frame. Although the results are ok as shown in my console, I cant seem to be apple to insert them in the same data frame, or even create a new one. Any help? I am grouping them first based on a column (postcode) and then performing the calculation for all rows with the same postcode. Thank you in advance

 my_data %>%
   group_by(as.character(Postcode))%>%
   summarise(wgt_inw_PC = sum(E_W_GEM))

enter image description here

2
Can you show a small reproducible example with dputakrun
sorry but i don't get what you mean. What I posted works and calculates the summation of all rows with the same postcode. the result in the console is a tibble with two columns. one with every postcode and the second with the calculated valueJohn Triantafyllidis
I meant a. small example data to tesstakrun
i added an image of the dataframeJohn Triantafyllidis
What is your expected outpu. You post is not clearakrun

2 Answers

1
votes

We just need to assign it back to the object

library(dplyr)
my_data <-  my_data %>%
                group_by(Postcode = Postcode)%>%
                summarise(wgt_inw_PC = sum(E_W_GEM, na.rm = TRUE))

Or another option is the compound assignment operator from magrittr (%<>%)

library(magrittr)
my_data %<>%
            group_by(Postcode = Postcode)%<>%
            summarise(wgt_inw_PC = sum(E_W_GEM, na.rm = TRUE))
1
votes

I am not sure if this is what you're looking for (I recommend using reproducible examples when asking questions on SO), but here's a code for conducting a calculation in groups and then appending this to your data frame:

library(dplyr)
#> 
#> Attaching package: 'dplyr'

mtcars %>%
    group_by(cyl)%>%
    mutate(wgt = sum(wt))

#> # A tibble: 32 x 12
#> # Groups:   cyl [3]
#>      mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb   wgt
#>    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1  21       6  160    110  3.9   2.62  16.5     0     1     4     4  21.8
#>  2  21       6  160    110  3.9   2.88  17.0     0     1     4     4  21.8
#>  3  22.8     4  108     93  3.85  2.32  18.6     1     1     4     1  25.1
#>  4  21.4     6  258    110  3.08  3.22  19.4     1     0     3     1  21.8
#>  5  18.7     8  360    175  3.15  3.44  17.0     0     0     3     2  56.0
#>  6  18.1     6  225    105  2.76  3.46  20.2     1     0     3     1  21.8
#>  7  14.3     8  360    245  3.21  3.57  15.8     0     0     3     4  56.0
#>  8  24.4     4  147.    62  3.69  3.19  20       1     0     4     2  25.1
#>  9  22.8     4  141.    95  3.92  3.15  22.9     1     0     4     2  25.1
#> 10  19.2     6  168.   123  3.92  3.44  18.3     1     0     4     4  21.8
#> # ... with 22 more rows