1
votes

I am trying to code weekends and weekdays using numeric values, such that "Monday","Tuesday",..."Friday" = 0 and "Saturday"/"Sunday" = 1. I presently have the following data:

head(bike.d)

    Day    Day.Code
    Sunday     4
    Sunday     4
    Sunday     4
    Sunday     4
    Sunday     4
    Sunday     4

tail(bike.d)

    Day    Day.Code
    Saturday   3
    Saturday   3
    Saturday   3
    Saturday   3
    Saturday   3
    Saturday   3

I have coded the Day column numerically using:

Day.Code = as.numeric(bike.d$Day)

Where Friday = 1, Monday = 2, Saturday = 3, Sunday = 4, Thursday = 5, Tuesday =6, Wednesday = 7.

I have tried to use logical operators to assign the binary values with weekdays =0 and weekends = 1. I have tried variations of the following argument, but I get the following output:

bike.d[,2 == 3|4]=1

head(bike.d)

    Day    Day.Code
     1         1
     1         1
     1         1
     1         1
     1         1
     1         1

tail(bike.d)

    Day    Day.Code
     1         1
     1         1
     1         1
     1         1
     1         1
     1         1

Is there a way I can create this argument so that the text values in the "Day" column is preserved? And so that the binary code is either input in the Day.code column, or a new column?

Thank you for your help!

1
Can you make your example reproducible? stackoverflow.com/questions/5963269/…Roman Luštrik
Look at merge, it will make your life easier.flodel

1 Answers

1
votes

An ifelse should be exactly what you need here (there are many other ways to do it):

bike.d$Weekend <- ifelse( bike.d$Day.Code == 3 | bike.d$Day.Code == 4 , 1 , 0 )

An example:

bike.d<- data.frame( Day = rep( weekdays(Sys.Date()+1:7) , each = 2 ) , Day.Code = rep( 1:7 , each = 2 ) )
bike.d$Weekend <- ifelse( bike.d$Day.Code == 3 | bike.d$Day.Code == 4 , 1 , 0 )
bike.d
#        Day Day.Code Weekend
#1   Thursday        1       0
#2   Thursday        1       0
#3     Friday        2       0
#4     Friday        2       0
#5   Saturday        3       1
#6   Saturday        3       1
#7     Sunday        4       1
#8     Sunday        4       1
#9     Monday        5       0
#10    Monday        5       0
#11   Tuesday        6       0
#12   Tuesday        6       0
#13 Wednesday        7       0
#14 Wednesday        7       0