Replace all values in a matrix <0.1 with 0

后端 未结 6 1216
执念已碎
执念已碎 2020-11-29 23:31

I have a matrix (2601 by 58) of particulate matter concentration estimates from an air quality model. Because real-life air quality monitors cannot measure below 0.1 ug/L,

6条回答
  •  一生所求
    2020-11-30 00:14

    I think you will find that 'ifelse' is not a vector operation (its actually performing as a loop), and so it is orders of magnitudes slower than the vector equivalent. R favors vector operations, which is why apply, mapply, sapply are lightning fast for certain calculations.

    Small Datasets, not a problem, but if you have an array of length 100k or more, you can go and cook a roast dinner before it finishes under any method involving a loop.

    The below code should work.

    For vector

    minvalue <- 0
    X[X < minvalue] <- minvalue
    

    For Dataframe or Matrix.

    minvalue <- 0
    n <- 10 #change to whatever.
    columns <- c(1:n)
    X[X[,columns] < minvalue,columns] <- minvalue
    

    Another fast method, via pmax and pmin functions, this caps entries between 0 and 1 and you can put a matrix or dataframe as the first argument no problems.

    ulbound <- function(v,MAX=1,MIN=0) pmin(MAX,pmax(MIN,v))
    

提交回复
热议问题