1

Using R, I want to grab the two most recently dated entries for each UserID, assuming there is 1 or more entries per UserID.

The key elements of my data would be an identifier (UserID), and a date, that is of type date.

Thank you.

4
  • What database are you using? Feb 24, 2017 at 4:09
  • MS 2014 I believe. I am game for using sqldf or sqlquery from the rodbc package.
    – Scottieie
    Feb 24, 2017 at 4:11
  • I gave you a query below. For the R side of things, any tutorial should get it done. Feb 24, 2017 at 4:13
  • Thanks. I am working it out now, noting that it is similar to a previous attempt. I will comment below your suggested solution.
    – Scottieie
    Feb 24, 2017 at 4:20

1 Answer 1

2

In SQL Server, which has the ROW_NUMBER() analytic function, you can try this query:

SELECT t.UserID, t.date, ...other columns
FROM
(
    SELECT UserID, date, ...other columns,
           ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY date DESC) rn
    FROM yourTable
) t
WHERE t.rn <= 2
4
  • Uh, wow! That worked like a champ and the syntax you specified makes sense to my feeble mind. I spent the better part of the day going back to this one. I even see where I goofed up. Thanks again.
    – Scottieie
    Feb 24, 2017 at 4:24
  • Happy to help you out. Feb 24, 2017 at 4:25
  • 1
    I just started a very different gig analyzing data (20 years of IT systems mgmt before) and decided to teach myself R. This site and the people who jump in to help are a blessing.
    – Scottieie
    Feb 24, 2017 at 4:28
  • @Scottieie I use it myself, q.v. the question I asked yesterday. Feb 24, 2017 at 4:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.