将数据汇总成整洁的格式

如何解决将数据汇总成整洁的格式

我已经汇总了我试图以“整洁”格式获取的数据。这是数据的示例。 1 级 = 同一组内所有 2 级或 3 级项目的总和。

灯 (2) 是电气 (1) 的子组件。 Wiring (3) 和 Bulbs (3) 是 Lights (2) 的子组件,依此类推。

200 电 = 82 灯 + 118 通风口

或者可以分解为:

200 个电气 = 60 个接线 + 22 个灯泡 + 60 个探测器 + 20 个电缆 + 25 个塑料 + 13 个支架

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     

然后对组 02(内部)重复该过程。我试图以整洁/更可行的格式获取这些数据,以便我可以进行一些分析,而无需重复或三次计算每件商品的价格。电气 (200) 和内部 (500) 的总和应该是 700。但是当我合计价格列时,我们得到 1840,因为项目被计算了不止一次。

解决方法

不是 tidyverse 但数据可以转换为 data.tree 和 igraph 格式,这些格式具有处理树和图形的功能,也可以用于转换为其他格式,例如as.list(nn) 其中 nn 是下面定义的 data.tree 节点对象是嵌套列表表示。有关可重现形式的输入数据,请参阅末尾的注释。

library(data.tree)
library(sqldf)
library(yaml)

# compute parents
DF2 <- sqldf("select a.*,max(b.rowid) parent
  from DF a
  left join DF b on b.Level = a.Level - 1 and b.rowid < a.rowid
  group by a.rowid")
# leaves are those rows that are not a parent
leaves <- setdiff(1:nrow(DF2),DF2$parent)

# format as a yaml string and then read the yaml into a data tree node structure
s <- sapply(1:nrow(DF2),function(i) with(DF2[i,],paste(
       if (Level == 1) paste0("Group-",Group,":\n"),strrep(" ",Level),paste0(i,Name),":",if (i %in% leaves) paste("\n","  Price:",Price)
     )))
y <- yaml.load(unlist(strsplit(s,"\n")))
nn <- as.Node(y)
print(nn,"Price")

给予(输​​出后继续)

                        levelName Price
1  Root                              NA
2   ¦--Group-1                       NA
3   ¦   °--1Electrical               NA
4   ¦       ¦--2Lights               NA
5   ¦       ¦   ¦--3Wiring           60
6   ¦       ¦   °--4Bulbs            22
7   ¦       °--5Vent                 NA
8   ¦           ¦--6Detector         60
9   ¦           ¦--7Cable            20
10  ¦           ¦--8Plastic          25
11  ¦           °--9Brackets         13
12  °--Group-2                       NA
13      °--10Interior                NA
14          ¦--11Doors               NA
15          ¦   °--12Knobs           40
16          °--13Trim                NA
17              °--14Shelves         NA
18                  °--15Brackets    50

我们也可以转换成 igraph 对象。

library(igraph)
set.seed(123)

g <- as.igraph(nn)
plot(g,vertex.shape = "none",vertex.label.cex = 0.7)

screenshot

注意

Lines <- "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"
DF <- read.table(text = Lines,header = TRUE)
,

我会通过删除任何汇总级别的行来解决这个问题,但首先要弄清楚它们属于哪个级别 1 和 2。请参见下面的示例,该示例依赖于您的数据在传入时按层次排序。例如,您现在可以对 Level1 或 Level2 求和。

library(tidyverse)

df_dups <- tribble(
   ~Level,~Group,~Name,~Price,1,01,'Electrical',200,2,'Lights',82,3,'Wiring',60,'Bulbs',22,'Vent',118,'Detector','Cable',20,'Plastic',25,'Brackets',13,02,'Interior',500,'Doors',300,'Knobs',40,'Trim','Shelves',150,4,50 
)

df_unique <- df_dups %>%
   mutate(
      NameLevel1=case_when(
         Level==1~Name,TRUE~NA_character_
      ),NameLevel2=case_when(
         Level==2~Name,NameLevel3=case_when(
         Level==3~Name,TRUE~NA_character_
      )
   ) %>%
   fill(NameLevel1,.direction="down") %>%
   fill(NameLevel2,.direction="down") %>%
   filter(Level==3) %>%
   select(Group,Name,Price,Level1=NameLevel1,Level2=NameLevel2)

df_unique
#> # A tibble: 8 x 5
#>   Group Name     Price Level1     Level2
#>   <dbl> <chr>    <dbl> <chr>      <chr> 
#> 1     1 Wiring      60 Electrical Lights
#> 2     1 Bulbs       22 Electrical Lights
#> 3     1 Detector    60 Electrical Vent  
#> 4     1 Cable       20 Electrical Vent  
#> 5     1 Plastic     25 Electrical Vent  
#> 6     1 Brackets    13 Electrical Vent  
#> 7     2 Knobs       40 Interior   Doors 
#> 8     2 Shelves    150 Interior   Trim

df_unique %>%
   group_by(Level1) %>%
   summarise(
      TotPrice=sum(Price),.groups="drop"
   )
#> # A tibble: 2 x 2
#>   Level1     TotPrice
#>   <chr>         <dbl>
#> 1 Electrical      200
#> 2 Interior        190

df_unique %>%
   group_by(Level1,Level2) %>%
   summarise(
      TotPrice=sum(Price),.groups="drop"
   )
#> # A tibble: 4 x 3
#>   Level1     Level2 TotPrice
#>   <chr>      <chr>     <dbl>
#> 1 Electrical Lights       82
#> 2 Electrical Vent        118
#> 3 Interior   Doors        40
#> 4 Interior   Trim        150

reprex package (v2.0.0) 于 2021 年 5 月 25 日创建

,

data.table 方法

split 这样的东西应该可以帮助您入门。

样本数据

library(data.table)
DT <- fread("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 ")

代码

split(DT,by = c("Group","Level"))

输出(列表)

$`1.1`
   Level Group       Name Price
1:     1     1 Electrical   200

$`1.2`
   Level Group   Name Price
1:     2     1 Lights    82
2:     2     1   Vent   118

$`1.3`
   Level Group     Name Price
1:     3     1   Wiring    60
2:     3     1    Bulbs    22
3:     3     1 Detector    60
4:     3     1    Cable    20
5:     3     1  Plastic    25
6:     3     1 Brackets    13

$`2.1`
   Level Group     Name Price
1:     1     2 Interior   500

$`2.2`
   Level Group  Name Price
1:     2     2 Doors   300
2:     2     2  Trim   200

$`2.3`
   Level Group    Name Price
1:     3     2   Knobs    40
2:     3     2 Shelves   150

$`2.4`
   Level Group     Name Price
1:     4     2 Brackets    50

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-