2
votes

I have a table

EmployeeSalary:

Date       | Salary
01.12.2016 | 2000
01.02.2016 | 3000
03.02.2016 | 5000
01.03.2017 | 1000
30.01.2017 | 5000
10.03.2017 | 1300

When the System Date is 13.03.2017. How to get the present month dates and the past month Dates (i.e., from February 1 to System date).

My code is :

start= format(Sys.Date() - 30, '%Y-%m-01') 
end=Sys.time() 
while (start<end)
{
  print(EmployeeSalary)
  EmployeeSalary$"Date" = EmployeeSalary$"Date"+1
}

Error which I get:

Error: non-numeric argument to binary Operator

Expected Output is :

EmployeeSalary:

Date       | Salary
01.02.2016 | 3000
03.02.2016 | 5000
01.03.2017 | 1000
10.03.2017 | 1300
1
I didn't understood what you need, but you can use seq() function with dates, ie, seq(Sys.Date(), by='month', length=3) outputs "2017-03-13" "2017-04-13" "2017-05-13".Fernando
To convert your date variable to an R Date-type , you can use as.Date. For example, as.Date("01.12.2016", "%m.%d.%Y") will return a date for the first cell.lmo
this command gives the sequence of months. But I Need the previous month and present month salary Details as mentioned in the EmployeeSalary tableMathumathi Anblagan

1 Answers

3
votes

Here is one way:

R> dates <- seq(Sys.Date(), length=62, by=-1)
R> mon <- function(d) as.integer(format(d, "%m")) %% 12
R> dates[mon(dates) >= mon(Sys.Date())-1]
 [1] "2017-03-13" "2017-03-12" "2017-03-11" "2017-03-10" "2017-03-09"
 [6] "2017-03-08" "2017-03-07" "2017-03-06" "2017-03-05" "2017-03-04"
[11] "2017-03-03" "2017-03-02" "2017-03-01" "2017-02-28" "2017-02-27"
[16] "2017-02-26" "2017-02-25" "2017-02-24" "2017-02-23" "2017-02-22"
[21] "2017-02-21" "2017-02-20" "2017-02-19" "2017-02-18" "2017-02-17"
[26] "2017-02-16" "2017-02-15" "2017-02-14" "2017-02-13" "2017-02-12"
[31] "2017-02-11" "2017-02-10" "2017-02-09" "2017-02-08" "2017-02-07"
[36] "2017-02-06" "2017-02-05" "2017-02-04" "2017-02-03" "2017-02-02"
[41] "2017-02-01"
R> 

We create sequence of dates going backwards. We then create helper function to get the (integer-valued) month for a date.

Given those two, we index the date sequence down to the ones matching your criteria: from this months or the preceding month.

And by taking 'month modulo 12' we also catch the case of January comparing to December.