r - 根据 R 中的列值复制行
问题描述
好的,我有以下数据集:
df = read.table(sep=",",
header=T,
text="combination,priority,boolean,value
0,1,True,1.4 #should be copied
0,2,True,2.0 #should be copied
1,1,True,3.2
1,2,True,54.2
2,1,False,12.1
2,2,False,44.1
")
有没有一种简洁的方法:
- 使用组合复制所有行
== 0
- 对于组合中的每个值
!=0
- AND 复制的行应该采用组合的值
!=0
。
预期输出:
df_new = read.table(sep=",",
header=T,
text="combination,priority,boolean,value
1,1,True,1.4 #copied row -> now comb==1
1,2,True,2.0 #copied row -> now comb==1
1,1,True,3.2
1,2,True,54.2
2,1,True,1.4 #copied row -> now comb==2
2,2,True,2.0 #copied row -> now comb==2
2,1,False,12.1
2,2,False,44.1
")
解决方案
使用 data.table,它有点复杂但可行:
library(data.table)
df <- setDT(df)
df_zero <- df[combination == 0]
# now combine the rows of df where combination !=0 with copies of the rows where
# combination does equal 0, taking on the non-zero combination values
df_zero <- df_zero[rep(seq_len(nrow(df_zero)), each = length(unique(df[combination!=0]$combination))), ]
df_zero[, combination := rep(unique(df[combination!=0]$combination), nrow(df[combination==0]))]
df <- rbind(df[combination!=0], df_zero)
df
combination priority boundry mean
1: 1 3 f 3.57246241
2: 1 3 t 0.22327863
3: 1 5 t 0.05760450
4: 2 3 f 3.47917124
5: 2 3 t 0.26262743
---
102: 14 5 t 0.05368306
103: 15 5 t 0.05368306
104: 16 5 t 0.05368306
105: 17 5 t 0.05368306
106: 18 5 t 0.05368306
推荐阅读
- groovy - 通过 Groovy 脚本在 SoapUI 中进行自动数据驱动测试
- python - 如何使用python从http url中删除文件夹
- hibernate - 防止休眠以记录敏感日期
- python - 动态透视表的有效方法
- memory - JNI API DestroyJavaVM 后 JVM 使用的空闲内存
- c# - 当我尝试使用 git push origin 显示它时,处理标准输出在 c# 中不起作用
- c - 我无法使用链表打印多项式表达式
- javascript - 使我的函数更可重用的提示
- sql-server - SQL 登录已创建但未映射 - 用户已存在 - 之间是否有任何联系?
- ios - 如何快速获取集合视图的当前索引路径