简体   繁体   English

如何在另一个因素的基础上计算一个因素

[英]How to count one factor on basis of another factor

Days   Sentiment
Mon     Positive
Tues    Negative
Wed     Positive
Thurs   Negative
Friday  Positive
Sat     Negative
Sun     Positive
Mon     Positive
Tues    Negative
Wed     Positive
Thurs   Negative
Friday  Positive
Sat     Negative
Sun     Positive

Using above data I want to create new data frame like given below. 使用以上数据,我想创建如下所示的新数据框。 It will count days as unique value and count number of positive or negative sentiments present in it. 它将天数作为唯一值,并计算其中出现的正面或负面情绪的数量。

Days       Positive     Negative
Mon         2              0
Tuesday     0              2
.
.
.
.

Prepare Data 准备数据

library(lubridate)
library(dplyr)
library(reshape2)

data <- data.frame(Days = rep(weekdays(seq(today(),(today() + days(6)), by = "day")),2),
                   Sentiment = sample(c("Positive","Negative"),14,replace = TRUE),stringsAsFactors = FALSE)

Use dplyr and reshpae2 使用dplyrreshpae2


data %>%
    group_by(Days, Sentiment) %>%
    summarise(count = n()) %>%
    dcast(Days ~ Sentiment, value = count) %>%
    mutate_all(~ifelse(is.na(.),0,.))
       Days Negative Positive
1    Friday        2        0
2    Monday        1        1
3  Saturday        1        1
4    Sunday        0        2
5  Thursday        0        2
6   Tuesday        2        0
7 Wednesday        1        1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM