0

I have the following data frame:

id        day           total_amount
 1       2016-06-09         1000
 1       2016-06-23          100
 1       2016-06-24          200
 1       2015-11-27         2392
 1       2015-12-16          123
 7       2015-07-09          200
 7       2015-07-09         1000
 7       2015-08-27       100018
 7       2015-11-25         1000

How can I throw away rows where day column is older than three weeks from today using both base R packages and other packages such as dplyr .

2 Answers 2

3

We can use subset

 subset(df1, as.Date(day) > Sys.Date()-21)
Sign up to request clarification or add additional context in comments.

2 Comments

subset(test_df, as.Date(day) > Sys.Date()-21) seems to be correct ,what is your idea?
@sanaz Corrected that. I thought it was the other way. Sorry
2

Just to fill in two additional possibilities (that are nearly identical to one another in terms of syntax and quite similar to @akrun's use of subset).

You can use with in as follows to shorten the number of characters:

with(df, df[as.Date(day) > Sys.Date()-21,])

As you mentioned a desire to see other packages, here is one way to drop old observations using the data.table package.

library(data.table)
# turn df into a data.table
setDT(df)

df[as.Date(day) > Sys.Date()-21,]

data

df <- read.table(header=T, text="id        day           total_amount
 1       2016-06-09         1000
 1       2016-06-23          100
 1       2016-06-24          200
 1       2015-11-27         2392
 1       2015-12-16          123
 7       2015-07-09          200
 7       2015-07-09         1000
 7       2015-08-27       100018
 7       2015-11-25         1000")

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.