I want to create 7 Dummy-Variables for all days of the week to my dataframe. My dataframe "BTC.USD" contains time series data of Bitcoin expressed in USD (Close = Closing Price):
# A tibble: 6 x 3
Date Close Wday
<date> <dbl> <ord>
1 2015-12-31 430. Do
2 2016-01-01 434. Fr
3 2016-01-02 434. Sa
4 2016-01-03 431. So
5 2016-01-04 433. Mo
6 2016-01-05 431. Di
(The abbreviations for Wday are in German)
How I can add 7 new columns with Dummy Variables for the days of the week?
Is it better to use a map- or a apply-function?
You can use weekdays()
to find the day of the week, then dcast()
.
tt <- "date close
2015-12-31 430
2016-01-01 434
2016-01-02 434
2016-01-03 431
2016-01-04 433
2016-01-05 431"
d <- read.table(text=tt, header=T, stringsAsFactors = F)
library(dplyr) # for mutate() and `%>%`
library(data.table) # for dcast()
d %>%
mutate(date = as.Date(date)) %>%
mutate(weekday = weekdays(date)) %>%
dcast(date + close ~ weekday, fun.aggregate = length)