-1

I have a data frame with entries such as

     GN      Datum     Land Wert
1 11747 2012-01-04 Thailand 7616
2 11747 2012-01-04 Thailand 6241
3 11747 2012-01-04 Thailand 1174
4 11747 2012-01-04 Thailand 2156

GN is the ID. But in this case, all four entries have the same ID. What I want is to summarize "Wert", so that in the end I have:

     GN      Datum     Land Wert
1 11747 2012-01-04 Thailand 17187

How can I do this? I know I should probably use plyr package or apply or something, but I am pretty clueless where to start.

Secondly, let's say there are more variables in the data frame, and I don't want to group by them or summarize them, I just want to take their value - assuming they all have the same value in each group. How do I preserve those?

grssnbchr
  • 2,877
  • 7
  • 37
  • 71
  • 1
    `library(dplyr); df %>% group_by(GN, Datum,Land) %>% summarise(Wert=sum(Wert))` or using `base R` `aggregate(Wert~., df, FUN=sum)` – akrun Jan 12 '15 at 14:11
  • Awesome. I didn't know how to correctly use the `summarise` function. – grssnbchr Jan 12 '15 at 14:13
  • 1
    @DavidArenburg, It may be a duplicate but based on the OP's comment under my answer, it's not a duplicate of the question you linked to.. – talat Jan 12 '15 at 14:27
  • @docendodiscimus I don't see any comment under your answer except akruns – David Arenburg Jan 12 '15 at 14:29
  • 1
    I've reopened, though I think you should try to include *all* the information in the first place rather than using `zoo::rolledit` every minute or too. – David Arenburg Jan 12 '15 at 14:30

1 Answers1

1

With base R you can do:

aggregate(Wert ~ ., df, sum)
#     GN      Datum     Land  Wert
#1 11747 2012-01-04 Thailand 17187

If you want to preserve other columns you have in your data, you can for example do (using dplyr):

df %>% group_by(GN, Datum, Land) %>% mutate(Wert = sum(Wert)) %>% slice(1)
#     GN      Datum     Land  Wert
#1 11747 2012-01-04 Thailand 17187

This will keep other columns and only leave the first row of each group of GN, Datum, Land.

talat
  • 68,970
  • 21
  • 126
  • 157