我使用data.tree
包来执行分析,而不是嵌套列表,因为我的实际数据最终导致列表过于嵌套,很难使用。
我根据这个问题整理了一些样本数据。用R聚合数据树上的值。在我自己的数据中,我有to, from, hours
数据,并且需要创建actual_hours
数据,该数据是从其父节点的hours
值减去的子节点的总和。
library(data.tree)
#Have
to <- c("Team1", "Team1-1","Team1-1", "Team1-1-1", "Team1-1-1", "Team1-1-1", "Team1-1-2")
from <- c("Team1-1", "Team1-1-1","Team1-1-2", "Team1-1-1a", "Team1-1-1b", "Team1-1-1c" ,"Team1-1-2a")
hours <- c(NA,150,200,65,20,30, 30)
df <- data.frame(from,to,hours)
# Create data tree
tree <- FromDataFrameNetwork(df)
###Current Output
print(tree, "hours")
levelName hours
1 Team1 NA
2 °--Team1-1 NA
3 ¦--Team1-1-1 150
4 ¦ ¦--Team1-1-1a 65
5 ¦ ¦--Team1-1-1b 20
6 ¦ °--Team1-1-1c 30
7 °--Team1-1-2 200
8 °--Team1-1-2a 30
#Need to create
actual_hours <- c(NA,35,170, 65,20,30, 30)
df <- data.frame(from,to,hours, actual_hours)
# Create data tree
tree <- FromDataFrameNetwork(df)
#Desired output
print(tree, "hours", 'actual_hours')
levelName hours actual_hours
1 Team1 NA NA
2 °--Team1-1 NA NA
3 ¦--Team1-1-1 150 35
4 ¦ ¦--Team1-1-1a 65 65
5 ¦ ¦--Team1-1-1b 20 20
6 ¦ °--Team1-1-1c 30 30
7 °--Team1-1-2 200 170
8 °--Team1-1-2a 30 30
我不知道该怎么做,因为它涉及到树的向上和向下运动?我认为使用树的height
和/或level
属性是可行的,但不确定。
假设data.tree看起来像这个
levelName hours
1 Team1 NA
2 °--Team1-1 0
3 ¦--Team1-1-1 150
4 ¦ ¦--Team1-1-1a 65
5 ¦ ¦--Team1-1-1b 20
6 ¦ °--Team1-1-1c 30
7 °--Team1-1-2 200
8 °--Team1-1-2a 30
这里有两个版本供你试用,因为我不确定你想要哪一个。
非累积
tree$Do(function(node) {
node$actual_hours <- node$hours - if (node$isLeaf) 0 else Aggregate(node, attribute = "hours", aggFun = sum)
}, traversal = "post-order")
> print(tree, "hours", "actual_hours")
levelName hours actual_hours
1 Team1 NA NA
2 °--Team1-1 0 -350 # see here, -350=0-(150+200)
3 ¦--Team1-1-1 150 35
4 ¦ ¦--Team1-1-1a 65 65
5 ¦ ¦--Team1-1-1b 20 20
6 ¦ °--Team1-1-1c 30 30
7 °--Team1-1-2 200 170
8 °--Team1-1-2a 30 30
累计
tree$Do(function(node) {
node$actual_hours <- node$hours - if (node$isLeaf) 0 else Aggregate(node, attribute = "actual_hours", aggFun = sum)
}, traversal = "post-order")
> print(tree, "hours", "actual_hours")
levelName hours actual_hours
1 Team1 NA NA
2 °--Team1-1 0 -205 # -205=0-(35+170)
3 ¦--Team1-1-1 150 35
4 ¦ ¦--Team1-1-1a 65 65
5 ¦ ¦--Team1-1-1b 20 20
6 ¦ °--Team1-1-1c 30 30
7 °--Team1-1-2 200 170
8 °--Team1-1-2a 30 30