当多行/列组合不满足要求时更改值
Posted
技术标签:
【中文标题】当多行/列组合不满足要求时更改值【英文标题】:Changing value when multiple rows/columns combined do not meet a requirement 【发布时间】:2015-12-14 12:58:55 【问题描述】:对 R 来说相对较新,正在处理一个有数百万行的项目,所以我做了这个例子: 我有一个包含三行不同数据的矩阵。 如果 [,1][,2][Farm] 的组合总共少于两个观测值,则该行的 [Farm] 值将更改为 q99999。这样它们就属于同一组以供以后分析。
A <- matrix(c(1,1,2,3,4,5,5), ncol = 7)
B <- matrix(c(T,T,F,T,F,T,T), ncol = 7)
C <- matrix(c("Req","Req","Req","fd","as","f","bla"), ncol = 7)
AB <- rbind.fill.matrix(A,B, C)
AB <-t(AB)
colnames(AB) <- c("Col1", "Col2", "Farm")
format(AB)
Col1 Col2 Farm
1 "1 " "1 " "Req"
2 "1 " "1 " "Req"
3 "2 " "0 " "Req"
4 "3 " "1 " "fd "
5 "4 " "0 " "as "
6 "5 " "1 " "f "
7 "5 " "1 " "bla"
所以预期的结果如下:
Col1 Col2 Farm
1 "1 " "1 " "Req"
2 "1 " "1 " "Req"
3 "2 " "0 " "q99999"
4 "3 " "1 " "q99999"
5 "4 " "0 " "q99999"
6 "5 " "1 " "q99999"
7 "5 " "1 " "q99999"
现在“Farm”列有两个组,“Req”和“q99999”
在 R 中,在保持性能尽可能快的同时完成这项工作的最佳方法是什么?
【问题讨论】:
【参考方案1】:使用data.table
包的可能解决方案:
library(data.table)
as.data.table(AB)[,Farm:=ifelse(.N>1, Farm, "q99999"),.(Col1, Col2, Farm)][]
# Col1 Col2 Farm
#1: 1 1 Req
#2: 1 1 Req
#3: 2 0 q99999
#4: 3 1 q99999
#5: 4 0 q99999
#6: 5 1 q99999
#7: 5 1 q99999
或以R
为基础ave
:
AB[,'Farm'] = ave(AB[,'Farm'], do.call(c,apply(AB,2,list)), FUN=function(x) ifelse(length(x)==1, 'q99999',x))
# Col1 Col2 Farm
#1 "1" "1" "Req"
#2 "1" "1" "Req"
#3 "2" "0" "q99999"
#4 "3" "1" "q99999"
#5 "4" "0" "q99999"
#6 "5" "1" "q99999"
#7 "5" "1" "q99999"
【讨论】:
很高兴为您提供帮助!如果不清楚,请随时就代码提出问题!以上是关于当多行/列组合不满足要求时更改值的主要内容,如果未能解决你的问题,请参考以下文章
RowDetailsTemplate 中的组合框在选定列之前更新所有内容
当多行满足要求时,如何通过连接在 PostgreSQL 中进行选择?