Lee
Lee

Reputation: 234

Ranking entries in a column based on sums of entries in another column

everyone. I am a beginner in R with a question I can't quite figure out. I've created multiple queries within Stack Overflow to address my question (links to results here, here, and here) but none have addressed my issue. On to the problem: I have subset data frame DAV from a larger dataset.

> str(DAV)

'data.frame':   994 obs. of  9 variables:

$ MIL.ID     : Factor w/ 18840 levels "","0000151472",..: 7041 9258 10513 5286 5759 5304 5312 5337 5337 5547 ...

$ Name       : Factor w/ 18395 levels "","  Atticus Finch",..: 1226 6754 12103 17234 2317 14034 15747 4542 4542 14819 ...

$ Center     : int  2370 2370 2370 2370 2370 2370 2370 2370 2370 2370 ...

$ Gift.Date  : Factor w/ 339 levels "","01/01/2015",..: 6 6 6 7 10 13 13 13 13 13 ...

 $ Gift.Amount: num  100 47.5 150 41 95 ...

$ Solic.     : Factor w/ 31 levels "","aa","ac","an",..: 20 31 20 29 20 8 28 8 8 8 ...

$ Tender     : Factor w/ 10 levels "","c","ca","cc",..: 3 2 3 5 2 9 3 9 9 9 ...
 $ Account    : Factor w/ 16 levels "","29101-0000",..: 4 4 4 11 2 11 2 11 2 11 ...

$ Restriction: Factor w/ 258 levels "","AAU","ACA",..: 216 59 216 1 137 1 137 1 38 1 ...

The two relevant columns for my issue are MIL.ID, which contains a unique ID for a donor, and Gift.Amount, which contains a dollar amount for a single gift the donor gave. A single MIL.ID is often associated with multiple Gift.Amount entries, meaning that donor has given on multiple different occasions for various amounts. Here is what I want to do:

  1. I want to separate out the above mentioned columns from the rest of the data frame;
  2. I want to sum(Gift.Amount) but only do so for each donor, i.e. I want to create a sum of all gifts for MIL.ID 1234 in the above data.frame; and
  3. I want to rank all the MIL.IDs based on the sum Gift.Amount entries associated with their ID.

I apologize for how basic this is, and if it is redundant to a question already asked, but I couldn't find anything.

Edit to address comment:

shot of table

    > print(ranking)

Desired output

I am struggling to get the formatting correct here so I included screen shots

Upvotes: 0

Views: 91

Answers (1)

Sotos
Sotos

Reputation: 51592

This should do it:

df <- DAV[, c("MIL.ID", "Gift.Amount")] #extract columns
df <- aggregate(Gift.Amount ~ MIL.ID, df, sum) #sum amounts with same ID
df <- df[ order(df$Gift.Amount,decreasing = TRUE), ] #sort Decreasing

Upvotes: 1

Related Questions