2016年6月15日水曜日

Calculate day dependent data with less workload - 2 - test 2 strings are equal or not

Use match function to test 2 strings are same or not.

Below is a normal case and easy.

> weekdays(as.Date("2016-01-01"),abbreviate = TRUE)
[1] "Fri"
match(weekdays(as.Date("2016-01-01"),abbreviate = TRUE),"Fri")
[1] 1

In other cases, match return NA not 0 by default and this causes a problem in if function. I see this is very strange, however, it is just one more option to go.

> match(weekdays(as.Date("2016-01-01"),abbreviate = TRUE),"Mon")
[1] NA

The parameter nomatch will give an option to set a value for the case. with "nomatch=0" you can booleanize the return value

> match(weekdays(as.Date("2016-01-01"),abbreviate = TRUE),"Fri", nomatch=0)
[1] 1
> match(weekdays(as.Date("2016-01-01"),abbreviate = TRUE),"Thur", nomatch=0)
[1] 0

Then now it's possible to use if-then-else clause without problem.

> if(match(weekdays(as.Date("2016-01-01"),abbreviate = TRUE),"Mon",nomatch=0)){print("金曜日")}else{print("other days...")}
[1] "other days..."
> if(match(weekdays(as.Date("2016-01-01"),abbreviate = TRUE),"Fri",nomatch=0)){print("金曜日")}else{print("other days...")}
[1] "金曜日"

0 件のコメント: