Changing value when multiple rows/columns combined do not meet a requirement

安稳与你 提交于 2020-01-06 04:08:05

问题


Relatively new to R, working on a project with millions of rows so I made this example:
I've got a matrix with three different rows of data.
If the combination of [,1][,2][Farm] has less then two observations in total, the [Farm] value of that row gets changed to q99999. This way they fall in the same group for later analysis.

    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"

So the expected result would be as following:

     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"

Now there is two groups for the column "Farm", "Req" and "q99999"

What would be the best way in R to get this done while keeping performance as quick as possible?


回答1:


A possible solution using data.table package:

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

Or base R with 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"


来源:https://stackoverflow.com/questions/32634025/changing-value-when-multiple-rows-columns-combined-do-not-meet-a-requirement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!