0

I have a large data frame (below) and my intention is to get dates into the last column DateToTake:

The condition I'm searching for is conditional on the variable weekday:

For weekdays from Monday to Friday I want the dates from the variable Date of the same row.

For "Saturday" I want the Date + 2 days (date of the following monday)

For "Sunday" I want the Date + 1 day (also the date of the following monday)

(e.g. in the data frame: for "Saturday" and "Sunday" I want the date of the following Monday, in the case below "2007-01-08")

         Date PX_OPEN PX_HIGH PX_LOW PX_LAST PX_VOLUME   weekday DatetoTake
1  2007-01-01      NA      NA     NA      NA        NA    Monday         NA
2  2007-01-02  597.00  602.67 596.83  602.61 107651752   Tuesday         NA
3  2007-01-03  602.73  604.55 601.72  603.79 154028672 Wednesday         NA
4  2007-01-04  601.15  602.49 598.85  601.92 191185072  Thursday         NA
5  2007-01-05  600.05  600.55 595.06  595.40 188421584    Friday         NA
6  2007-01-06      NA      NA     NA      NA        NA  Saturday         NA
7  2007-01-07      NA      NA     NA      NA        NA    Sunday         NA
8  2007-01-08  597.09  598.25 594.73  596.66 158539856    Monday         NA
9  2007-01-09  598.21  601.60 597.22  597.65 183998640   Tuesday         NA
10 2007-01-10  594.93  595.32 590.82  593.39 201679808 Wednesday         NA

Has anybody an idea how this could work in R?

hpesoj626
  • 3,529
  • 1
  • 17
  • 25
Chellarioo
  • 27
  • 1
  • 6

1 Answers1

1

Here is a dplyr solution.

tt <- 'Date PX_OPEN PX_HIGH PX_LOW PX_LAST PX_VOLUME   weekday DatetoTake
1  2007-01-01      NA      NA     NA      NA        NA    Monday         NA
2  2007-01-02  597.00  602.67 596.83  602.61 107651752   Tuesday         NA
3  2007-01-03  602.73  604.55 601.72  603.79 154028672 Wednesday         NA
4  2007-01-04  601.15  602.49 598.85  601.92 191185072  Thursday         NA
5  2007-01-05  600.05  600.55 595.06  595.40 188421584    Friday         NA
6  2007-01-06      NA      NA     NA      NA        NA  Saturday         NA
7  2007-01-07      NA      NA     NA      NA        NA    Sunday         NA
8  2007-01-08  597.09  598.25 594.73  596.66 158539856    Monday         NA
9  2007-01-09  598.21  601.60 597.22  597.65 183998640   Tuesday         NA
10 2007-01-10  594.93  595.32 590.82  593.39 201679808 Wednesday         NA'

library(dplyr)
df <- read.table(text = tt, header = T, na.strings = 'NA')
df2 <- df %>%
  mutate(
    DatetoTake = case_when(
      weekday %in% c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') ~ as.Date(Date),
      weekday == 'Saturday'~as.Date(Date) + 2,
      weekday == 'Sunday'~as.Date(Date) + 1
      )
  )
hpesoj626
  • 3,529
  • 1
  • 17
  • 25
  • 1
    If you found that the answer solves your problem, please [accept it](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – rollstuhlfahrer Mar 27 '18 at 15:40