Nyxynyx
Nyxynyx

Reputation: 63619

Create a Dummy/Categorial Variable based on Day of Week in R

I'm new to R and is attempting to test out the "January Effect" to see if there is higher returns on Mondays.

I think this involves creating a dummy variable monday that takes the value of 1 if it is a Monday and 0 otherwise.

Question: How can the dummy variable monday be created, given that spyReturns contains the dates.

library(quantmod)
getSymbols('SPY', from='2015-01-01')
spyReturns <- dailyReturn(SPY)

monday <- #?? How to identify mondays?
lm(spyReturns ~ factor(monday))

Upvotes: 1

Views: 2161

Answers (2)

user3710546
user3710546

Reputation:

In help page of strptime, arguments %u and %w can be used. Thus, with:

monday <- as.numeric(format(index(spyReturns), "%u") %in% "1")

We get

#  [1] 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0
# [38] 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 1
# ...

Upvotes: 2

Shiva Prakash
Shiva Prakash

Reputation: 1919

data$weekday <- format(data$date, "%A")

# creating a dummy variable ###########
data$monday <- 0 
data[data$weekday == "Monday",]$monday <- 1 

This is should solve the problem. In case if you need to create dummy for all the weekday, you can just use a loop to do the work.

Upvotes: 1

Related Questions