如何通过ifelse和标签分隔矢量?

时间:2014-01-20 12:44:18

标签: r

我正在尝试将chisq.test应用于一周的刑事统计数据。在里面 第一次ChiSquare测试我意识到日子不是平均分配的。

首先是Chisq.test

DAYS = c("So"=53, "Mo"=42, "Di"=51, "Mi"=45, "Do"=36, "Fr"=37, "Sa"=65)
DAYS

So Mo Di Mi Do Fr Sa 
53 42 51 45 36 37 65 

chisq.test(DAYS)

    Chi-squared test for given probabilities

        data:  DAYS
        X-squared = 13.3191, df = 6, p-value = 0.03824

作为下一个问题,我想查看工作日(周一至周五)和周末(周六+周日)的预期分布情况。我尝试将ifelse语句分成小组周末和工作日。但是,生成的week变量仅包含weekdayweekend

如何按标签划分数组以达到类似下面的效果?

希望的输出就像

week
weekend weekday
118     211

我是如何尝试将其分开的

week <- ifelse(DAYS %in% c("So", "Sa"), "weekend", "workday")

week
"workday" "workday" "workday" "workday" "workday" "workday"

1 个答案:

答案 0 :(得分:1)

你快到了:

week <- ifelse(names(DAYS) %in% c("So", "Sa"), "weekend", "workday")
week
[1] "weekend" "workday" "workday" "workday" "workday" "workday" "weekend"

然后

DAYS_df <- data.frame(DAYS)
DAYS_df$week <- as.factor(ifelse(names(DAYS) %in% c("So", "Sa"), "weekend", "workday"))
by(DAYS_df$DAYS, DAYS_df$week, sum)
DAYS_df$week: weekend
[1] 118
----------------------------------------------------------------------------------- 
DAYS_df$week: workday
[1] 211