我有关于移动、往返的数据,并且想要说明有关某个位置的信息,例如,有多少东西从位置 1 进出。
test = data.table(day = c(1,1,1), from = c(1,2,1), to =c(3,1,3))
test[ , `:=`( total_from = .N) , by = c("day", "from") ]
test[ , `:=`( total_to = .N) , by = c("day", "to") ]
day from to total_from total_to
1: 1 1 3 2 2
2: 1 2 1 1 1
3: 1 1 3 2 2
我不能简单地添加两个总列,因为它们与同一位置不相关。 我更好的结果是:
day location count
1: 1 1 3
2: 1 2 1
3: 1 3 2
我不知道要搜索什么,因为我很确定 R 有一些这方面的功能,所以也许如果有人可以给我指明正确的方向,那会非常有帮助。
最佳答案
您拥有的是图形数据。每个位置都称为顶点或节点(它们是可以互换的),并且您尝试计算的数量称为度一个节点。 “入度”为流入总量,“出度”为流出总量;整体的“度”是两者之和。
有两种可能的解决方案:
- 通过 reshape 数据并求和来计算入度和出度,如 Jaap 的评论中
- 使用图库高效构建图并计算度。
我将演示两者。
reshape
第一个解决方案使用 data.table
中的“ reshape ”功能,因为您已经在使用该包:
test <- data.table(
day = c(1,1,1),
from = c(1,2,1),
to = c(3,1,3)
)
您的数据当前采用“宽”格式:您的两列彼此不同,即在给定日期流入或流出节点的数量。
test_long <- melt(test, id.vars = "day", variable.name = "direction", value.name = "location")
melt
将此数据 reshape 为“长”格式:一列指示位置,另一列指示方向。现在,您只需按日期和位置进行分组并计算每组的实例数即可轻松获得答案:
test_totals <- test_long[, .N, by = .(day, location)]
图形分析
幸运的是,data.table
对于“groupby”操作非常有效。
然而,图数据结构通常更加灵活和高效。 igraph是一个功能强大且易于使用的图形分析包,由精心构建的 C 库支持。
library(igraph)
test <- data.table(
day = c(1,1,1),
from = c(1,2,1),
to = c(3,1,3)
)
# the first 2 columns must be the vertices; each row is an edge
# other columns are treated as edge attributes
g <- graph.data.frame(test[, .(from, to, day)]
# returns a named vector of degree for each node
totals <- degree(g)
关于r - 匹配来去位置数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52778248/