Reputation: 3
I have a variable that starting from Monday that lists each date from 1-7. I want to change this to weekday vs. weekend, with a 0-1 respectively to create a dummy variable. I know how to do one, but I can't figure out how to include 6 AND 7 in iterations of the code.
For example, I put the following:
flights$dayweek <-factor(ifelse(as.numeric(flights$dayweek)==6, 1,0))
My intent for the above is for the code to find anywhere it says 6 & 7, then replace it with 1 and anything else is 0 for the variable dayweek in the flights data set. The problem with the above is it only does 6 and NOT 7. I don't know how to include 7 in the data set. I have tried:
flights$dayweek <-factor(ifelse(as.numeric(flights$dayweek)==6:7, 1,0))
flights$dayweek <-factor(ifelse(as.numeric(flights$dayweek)==c(6,7), 1,0))
And I have looked at other common dummy variables topics, but they all seem to be simple 1 to 0 like male/female and I know how to do that. Could I do a greater than 5 function? Sample data below:
schedtime carrier deptime dest distance date dayweek daymonth delay
1700 RU 1651 WER 213 1401 4 1 ontime
1800 RU 1402 EWR 199 1401 6 1 delayed
Upvotes: 0
Views: 447
Reputation: 4899
Use the %in%
operator to test inclusion in a vector.
# using an example dataset
flights <- data.frame(dayweek = rep(1:7, 2), "flight" = letters[1:14])
flights$dayweek <-factor(ifelse(as.numeric(flights$dayweek) %in% c(6, 7), 1,0))
> flights
dayweek flight
1 0 a
2 0 b
3 0 c
4 0 d
5 0 e
6 1 f
7 1 g
8 0 h
9 0 i
10 0 j
11 0 k
12 0 l
13 1 m
14 1 n
Upvotes: 1