列值相同时汇总列

时间:2016-06-23 06:26:05

标签: r aggregate

我手头有问题,我有两个向量,如下所示:

login_time  "08:00" "09:00" "09:00" "09:00" "09:00" "09:00" "09:00" "10:00" "11:00" "10:00" "10:00" "16:00" "17:00" "20:00" "21:00"
login_count 1     4     3     9     17    10    4     7     9     3     8     6     7     2     3    

现在,当第一行中的时间有多个值时,我应该总结登录计数值,最后我应该有唯一的login_time值,总计登录计数。

2 个答案:

答案 0 :(得分:2)

我们可以使用xtabs中的base R

xtabs(login_count~login_time)
#08:00 09:00 10:00 11:00 16:00 17:00 20:00 21:00 
#   1    47    18     9     6     7     2     3 

答案 1 :(得分:1)

您可以使用包dplyr

执行此操作
library(dplyr)
tmp_df <- data.frame(login_time = c("08:00","09:00","09:00","09:00","09:00","09:00","09:00","10:00","11:00","10:00","10:00","16:00","17:00","20:00","21:00"),
login_count  = c(1,4,3,9,17,10,4,7,9,3,8,6,7,2,3))

tmp_df %>%
    group_by(login_time) %>%
    summarise(total_logins = sum(login_count))

产生:

Source: local data frame [8 x 2]

  login_time total_logins
      (fctr)        (dbl)
1      08:00            1
2      09:00           47
3      10:00           18
4      11:00            9
5      16:00            6
6      17:00            7
7      20:00            2
8      21:00            3