## Changing Weekday into a categorical variable- Beg/End of Week
set.seed(123)
df <- data.frame(Absenteeism$Weekday)
df$category[Absenteeism$Weekday <= 3] <- "Beginning of Week"
df$category[Absenteeism$Weekday >= 4 ] <- "End of Week"
weekdaycat <- cut(Absenteeism$Weekday, breaks=c(0,3,7), labels=c("Beginning of Week","End of Week"))
summary(weekdaycat)
Absenteeism$Weekday <- as.factor(Absenteeism$Weekday)
summary(Absenteeism$Weekday)
R的新手,我设法将工作日数据归为一类,但现在我需要将其以week = 0
的开头和week = 1
的结尾进行二进制化。
有人可以帮我吗?谢谢。
答案 0 :(得分:0)
也许这就是您想要的:
# Made up weekdays as an example
Absenteeism <- data.frame(Weekday = (1:10)%%7+1)
# Create a new column with the explicit name
Absenteeism$categoryName = ifelse( Absenteeism$Weekday <= 3, "Beginning of Week", "End of Week")
# Create a new factors column with levels 0 and 1
Absenteeism$category = factor(ifelse( Absenteeism$Weekday <= 3, 0, 1))
结果:
> Absenteeism
Weekday categoryName category
1 2 Beginning of Week 0
2 3 Beginning of Week 0
3 4 End of Week 1
4 5 End of Week 1
5 6 End of Week 1
6 7 End of Week 1
7 1 Beginning of Week 0
8 2 Beginning of Week 0
9 3 Beginning of Week 0
10 4 End of Week 1
> summary(Absenteeism)
Weekday categoryName category
Min. :1.00 Length:10 0:5
1st Qu.:2.25 Class :character 1:5
Median :3.50 Mode :character
Mean :3.70
3rd Qu.:4.75
Max. :7.00