-3

I created a data frame of the following type

Name Date      Value
A    01.01.01  10  
B    02.01.01  2  
A    04.01.01  4  
...

I would like to obtain a list that ranks the elements in the name column by the total sum, provided that the dates are within a certain range.

rnso
  • 23,686
  • 25
  • 112
  • 234
SBFin
  • 352
  • 1
  • 9

1 Answers1

1

Welcome to Stack Overflow (SO). It is very important for anybody asking questions to provide reproducible data which you can get using dput(). Please read this link. If you have tried something, you want to leave your code and describe what your challenge is. In this way, you can help SO users save more time and you are likely to receive more support. Here, I did my best to read your question, created a sample data, and did the following using the dplyr package.

# Sample data 
foo <- data.frame(id = c("A", "B", "A", "C", "D", "B", "D", "E", "A", "S", "B"),
                  date = c("01.01.01", "02.01.01", "04.01.01", "05.01.01",
                           "11.01.01", "09.03.01", "12.15.01", "08.08.01",
                           "03.27.01", "11.16.01", "04.07.01"),
                  value = c(-10, -2, -4, 8, 5, 2, 10, 5, 11, 7, 8),
                  stringsAsFactors = FALSE)

#   id     date value
#1   A 01.01.01   -10
#2   B 02.01.01    -2
#3   A 04.01.01    -4
#4   C 05.01.01     8
#5   D 11.01.01     5
#6   B 09.03.01     2
#7   D 12.15.01    10
#8   E 08.08.01     5
#9   A 03.27.01    11
#10  S 11.16.01     7
#11  B 04.07.01     8

library(dplyr)

foo %>%
    # Create date objects
    mutate(date = as.Date(date, format = "%m.%d.%y")) %>%
    # Select data points which stay between 2001-01-01 and 2001-08-31
    filter(between(date, as.Date("2001-01-01"), as.Date("2001-08-31"))) %>%
    # For each id group
    group_by(id) %>%
    # Get sum of value
    summarise(Total = sum(value)) %>%
    # Arrange row order by descending order with Total
    arrange(desc(Total))

#  id Total
#1  C     8
#2  B     6
#3  E     5
#4  A    -3
Community
  • 1
  • 1
jazzurro
  • 23,179
  • 35
  • 66
  • 76
  • Thanks a lot, jazzurro! I'm sorry for not being specific enough on my problem and for the syntax of the question I posted. I am an R novice and at the moment I do not have an overview of the most useful packages for a specific problem out there. I was able to solve the problem with your help. – SBFin Nov 06 '14 at 22:20
  • @SBFin You are welcome. Great to hear that you solved the problem! – jazzurro Nov 06 '14 at 23:22