gpt4 book ai didi

递归运算符(operator)工和主管数据以在 R 中生成组织树层次结构

转载 作者:行者123 更新时间:2023-12-04 10:08:15 25 4
gpt4 key购买 nike

我通常分析“组织树”格式的数据,以了解码织内给定领导者的事件频率。我需要从两列数据生成一个广泛的层次结构:员工姓名和主管姓名。

----------
df <- data.frame("Employee"=c("Bill","James","Amy","Jen","Henry"),
"Supervisor"=c("Jen","Jen","Steve","Amy","Amy"))
df
# Employee Supervisor
# 1 Bill Jen
# 2 James Jen
# 3 Amy Steve
# 4 Jen Amy
# 5 Henry Amy

以指定组织结构图的宽数据框结束,从 CEO(或最高层员工)开始:

#  Employee       H1     H2    H3
# 1 Bill Steve Amy Jen
# 2 James Steve Amy Jen
# 3 Amy Steve NA NA
# 4 Jen Steve Amy NA
# 5 Henry Steve Amy NA

经过大量研究,data.tree 包似乎提供了最大的帮助。如何执行此操作?

最佳答案

试试这个:

library(data.table)
setDT(df)

setnames(df, 'Supervisor', 'Supervisor.1')

j=1
while (df[, any(get(paste0('Supervisor.',j)) %in% Employee)]) {
df[df, on=paste0('Supervisor.',j,'==Employee'),
paste0('Supervisor.',j+1):= i.Supervisor.1]
j = j + 1
}

> df
# Employee Supervisor.1 Supervisor.2 Supervisor.3
# 1: Bill Jen Amy Steve
# 2: James Jen Amy Steve
# 3: Amy Steve NA NA
# 4: Jen Amy Steve NA
# 5: Henry Amy Steve NA

在行内重新排序:

df = cbind(df[, 1], t(apply(df[, -1], 1, function(r) c(rev(r[!is.na(r)]), r[is.na(r)]))))
> df
# Employee V1 V2 V3
# 1: Bill Steve Amy Jen
# 2: James Steve Amy Jen
# 3: Amy Steve NA NA
# 4: Jen Steve Amy NA
# 5: Henry Steve Amy NA

关于递归运算符(operator)工和主管数据以在 R 中生成组织树层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44527883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com