将列分组为R数据帧中的计数

时间:2016-10-13 19:48:04

标签: r dataframe dplyr

所以我在数据框中总共有4个不同的cols

keyboard

所以我有以下问题:

是否可以使用r对以下内容进行分组,以便它可以成为类似的东西?

     port            ip                service      numberOfTimes
1     22         11.11.79.100            ssh           16
2     80         11.11.79.100            www           19
3     111        11.13.79.110            ipw           21
4     123        11.13.79.110            ssh           50
5     22         64.50.80.140            cde           45
6     80         64.50.80.140            www           16
7     22         71.11.64.100            ssh           234
8     80         71.11.64.100            you           33
9     22         100.15.31.1             ssh           99
10    41         120.15.31.12            has           19

等等其他端口

1 个答案:

答案 0 :(得分:2)

使用dplyr,这非常简单:

testData %>%
  group_by(port, service) %>%
  summarise(`Number of IPs` = n_distinct(ip)
            , `Total number of times` = sum(numberOfTimes))

您所包含的样本数据包含:

   port service `Number of IPs` `Total number of times`
  <int>   <chr>           <int>                   <int>
1    22     cde               1                      45
2    22     ssh               3                     349
3    41     has               1                      19
4    80     www               2                      35
5    80     you               1                      33
6   111     ipw               1                      21
7   123     ssh               1                      50

如果您遇到某种错误(在评论中提到),您需要在人们可以帮助您之前提供实际导致该错误的数据。

相关问题