问题描述
我有一些分层数据,我正试图将这些数据放入更相关的样式表中。我想将一列变异到我的数据框,告诉我每一行的父级。在这里,Lights 是 Electrical 的子类,而 Wiring 和 Bulbs 都是 Lights 的子类,依此类推。有没有办法我可以说“如果 Level = 2,在数据框中找到它上方最近的 Level 1,并将其分配为它的父级?”另一个示例是:如果该行是 3 级项目(布线),则其父项将是数据帧(灯光)中离它最近的 2 级项目。
因为数据是分层存储的,所以我需要它上面最近的级别。
ProductID ProductName Lat Long
1 Prod 1 34.00010 -118.0010
2 Prod 2 34.00020 -118.0020
3 Prod 3 34.00030 -118.0030
4 Prod 4 34.00030 -118.0030
期望的输出类似于:
Level Group Name Price
1 01 Electrical 200
2 01 Lights 82
3 01 Wiring 60
3 01 Bulbs 22
2 01 Vent 118
3 01 Detector 60
3 01 Cable 20
3 01 Plastic 25
3 01 Brackets 13
1 02 Interior 500
2 02 Doors 300
3 02 Knobs 40
2 02 Trim 200
3 02 Shelves 150
4 02 Brackets 50
解决方法
这是一种方法,但我认为应该有其他更好/更有效的解决方案。
while read -r INPUT
do
#Append spaces to prevent substring matching
if [[ $(echo " $@ " | grep -i " ${INPUT} " | wc -l) -eq 1 ]]
then
break
fi
done
我们创建和 library(dplyr)
library(purrr)
df %>%
mutate(ID = row_number()) %>%
group_by(Group) %>%
mutate(Parent = map2_dbl(Level,ID,~{
tmp <- ID[Level == .x - 1]
val <- tmp - .y
if(any(val < 0)) max(tmp[val < 0]) else NA
})) %>%
ungroup
# Level Group Name Price ID Parent
# <int> <int> <chr> <int> <int> <dbl>
# 1 1 1 Electrical 200 1 NA
# 2 2 1 Lights 82 2 1
# 3 3 1 Wiring 60 3 2
# 4 3 1 Bulbs 22 4 2
# 5 2 1 Vent 118 5 1
# 6 3 1 Detector 60 6 5
# 7 3 1 Cable 20 7 5
# 8 3 1 Plastic 25 8 5
# 9 3 1 Brackets 13 9 5
#10 1 2 Interior 500 10 NA
#11 2 2 Doors 300 11 10
#12 3 2 Knobs 40 12 11
#13 2 2 Trim 200 13 10
#14 3 2 Shelves 150 14 13
#15 4 2 Brackets 50 15 14
列,它是数据框中的行号,对于组中的每个 ID
,我们找出最接近的 Level
值,它比当前级别高一个级别。