1

I want to create a function in R that solves the following problem. I have a sample of returns (call this vector x), each one with a corresponding date (call this vector y). Since we have returns, the date vector y has only "trading days" (i.e. from Monday to Friday). I want to create a function that does the following:

The function has two inputs: a date and an integer (positive).

  1. R searches in the date vector y for the date entered by the user.

  2. Say the integer entered by the user was m; m > 0. Now, R takes the specified date and m dates BEFORE that one. (If m < 0, R must tell you there's an error.)

  3. R subsets the date vector y based on m and also the return vector x.

For a sake of an example, let's say I have 5 dates in "%m/%d/%Y" format.

01/01/2016    -2%
01/04/2016    +3%
01/05/2016    +1%
01/06/2016    -5%
01/07/2016    +3%

Now, if I enter into the function: f(01/06/2016, 2), then I would be left with:

01/05/2016    +1%
01/06/2016    -5%

I know this is quite specific, but it would teach me a lot about subsetting. (I haven't been able to find anything similar to this.)

alistaire
  • 42,459
  • 4
  • 77
  • 117
  • It's customary to make an attempt to work on your problem yourself then post the reproducible code and data if you run into a problem http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Hack-R Jun 09 '16 at 22:48
  • I understand. I am very new to R, so I only know the very basics. I don't have the slightest clue as to where to start with this problem. I searched for several webpages about subsetting in R but none were helpful. I'm very sorry, I tried to write a good example though. Nevertheless, thanks for the heads-up, I'll take this into consideration when I post anything else. – Alexis Solis Jun 09 '16 at 22:55
  • Fair enough. I took at stab at it. HTH – Hack-R Jun 09 '16 at 23:15

1 Answers1

0
y <- c(Sys.Date(),Sys.Date()+2,Sys.Date()+1,Sys.Date()-1,Sys.Date()-2,Sys.Date()-3)
x <- c(10,100,12,13,14,15)
df <- data.frame(y,x)

myfun <- function(d=d,m=0){
  # R searches in the date vector y for the date entered by the user.  
  # Say the integer entered by the user was m; m > 0. 
  # Now, R takes the specified date and m dates BEFORE that one. 
  # (If m < 0, R must tell you there's an error.)
  if(m < 0){
    cat("I must tell you, there's an error!") #trycatch is better
  }
  d <- as.Date(d)-m
  print(d)
  df1 <- df[df$y < (d+1),]
  return(df1)
}

myfun("2016-06-09", 0)

[1] "2016-06-09"
           y  x
1 2016-06-09 10
4 2016-06-08 13
5 2016-06-07 14
6 2016-06-06 15

That should do the trick. Nothing too fancy. You have to make sure to enter the date in the right format.

If you want to improve this you could make some control flow logic using format or the package lubridate to accept any date format and/or you could handle errors with tryCatch (see ?tryCatch).

Hack-R
  • 22,422
  • 14
  • 75
  • 131