计算R中多个变量的实例

ike*_*ike 4 r dplyr

我有一个大型数据表Divvy(超过240万条记录),如此显示(删除了一些列):

X   trip_id     from_station_id.x   to_station_id.x 
 1  1109420     94                  69
 2  1109421     69                  216
 3  1109427     240                 245
 4  1109431     113                 94
 5  1109433     127                 332
 3  1109429     240                 245
Run Code Online (Sandbox Code Playgroud)

我想找到从每个车站到每个对站的旅行次数.所以,例如,

From X     To Y     Sum
94         69       1
240        245      2
Run Code Online (Sandbox Code Playgroud)

等等然后使用dplyr将它连接到初始表,以制作类似下面的内容,然后将其限制为不同于from_station_id/to_combos,我将用它来映射路由(我有每个站的lat/long):

X   trip_id     from_station_id.x   to_station_id.x   Sum 
 1  1109420     94                  69                1
 2  1109421     69                  216               1
 3  1109427     240                 245               2
 4  1109431     113                 94                1
 5  1109433     127                 332               1
 3  1109429     240                 245               1
Run Code Online (Sandbox Code Playgroud)

我成功地用count来获得一些,例如:

count(Divvy$from_station_id.x==94 & Divvy$to_station_id.x == 69)
  x    freq
1 FALSE 2454553
2  TRUE      81
Run Code Online (Sandbox Code Playgroud)

但这显然是劳动密集型的,因为有300个独特的站点,所以超过44k的组合.我创建了一个帮助表,以为我可以循环它.

n <- select(Divvy, from_station_id.y )

  from_station_id.x 
1                94                
2                69                
3               240               
4               113               
5               113               
6               127               

   count(Divvy$from_station_id.x==n[1,1] & Divvy$to_station_id.x == n[2,1])

      x    freq
1 FALSE 2454553
2  TRUE      81
Run Code Online (Sandbox Code Playgroud)

我觉得像是一个循环

output <- matrix(ncol=variables, nrow=iterations)


output <- matrix()
for(i in 1:n)(output[i, count(Divvy$from_station_id.x==n[1,1] & Divvy$to_station_id.x == n[2,1]))
Run Code Online (Sandbox Code Playgroud)

应该工作,但想到它仍将只返回300行,而不是44k,所以它必须循环回来做n [2]&n [1]等...

我觉得可能还有一个更快的dplyr解决方案,让我返回每个组合的计数并直接附加它而不需要额外的步骤/表创建,但我还没有找到它.

我是R的新手,我已经四处寻找/认为我很接近,但我无法将最后一点加入Divvy.任何帮助赞赏.

Met*_*ics 5

#Here is the data.table solution, which is useful if you are working with large data: 
library(data.table)
setDT(DF)[,sum:=.N,by=.(from_station_id.x,to_station_id.x)][] #DF is your dataframe

   X trip_id from_station_id.x to_station_id.x sum
1: 1 1109420                94              69   1
2: 2 1109421                69             216   1
3: 3 1109427               240             245   2
4: 4 1109431               113              94   1
5: 5 1109433               127             332   1
6: 3 1109429               240             245   2
Run Code Online (Sandbox Code Playgroud)