Natasha R.
Natasha R.

Reputation: 531

How to apply a function to every nth month in data frame?

I have a data frame like this:

Month   Amount
1/31/2014   793
2/28/2014   363
3/31/2014   857
4/30/2014   621
5/31/2014   948
6/30/2014   385

I would like to apply a function (x*0.5) to the third and sixth rows in this data frame. The results will overwrite the data currently in the data frame. So the end result would look like this:

Month   Amount
1/31/2014   793
2/28/2014   363
3/31/2014   428.5
4/30/2014   621
5/31/2014   948
6/30/2014   192.5

I've tried the rollapply() function, but that functions seems to start at the first row only without an option to force it to start at the third.

I really appreciate any help around this. Thanks in advance.

Upvotes: 1

Views: 239

Answers (3)

C-x C-c
C-x C-c

Reputation: 1311

Suppose your data.frame is named DT:

DT$Amount[c(3,6)] <- 0.5 * DT$Amount[c(3,6)]

If you have a lot of data, use data.table:

setDT(DT)
DT[
  month(as.Date(Month, format = "%m/%d/%Y")) %% 3 == 0, 
  Amount := 0.5 * Amount
]

Upvotes: 1

Edu
Edu

Reputation: 903

An alternative for detecting particular months in bigger datasets is using month from lubridate()

  month ammount
1 1/31/2014     793
2 2/28/2014     363
3 3/31/2014     857
4 4/30/2014     621
5 5/31/2014     948
6 6/30/2014     385

library(lubridate)

df %>% mutate(month = as.Date(month, "%m/%d/%Y"),
         date_month = month(month),
         new_ammount =  ifelse(date_month %in% c(3,6), ammount*0.5, ammount))

Which provides

     month ammount date_month new_ammount
1 2014-01-31     793          1       793.0
2 2014-02-28     363          2       363.0
3 2014-03-31     857          3       428.5
4 2014-04-30     621          4       621.0
5 2014-05-31     948          5       948.0
6 2014-06-30     385          6       192.5

Upvotes: 0

manotheshark
manotheshark

Reputation: 4367

If the rows follow a pattern then %% can be used to select every x rows

df1$Amount[seq_len(nrow(df1)) %% 3 == 0] <- df1$Amount[seq_len(nrow(df1)) %% 3 == 0] * 0.5

      Month Amount
1 1/31/2014  793.0
2 2/28/2014  363.0
3 3/31/2014  428.5
4 4/30/2014  621.0
5 5/31/2014  948.0
6 6/30/2014  192.5

Upvotes: 0

Related Questions