Search code examples
rdataframerowdplyr

set to zero row values lover than rowmean


I have a dataframe that looks like this

 v1 v2 v3 v4 v5 
 4   1  3  4  3
 2   2  2  1  1
 2   10 2  1  2
 etc.

I want to transform the dataframe such that just raw values higher than raw mean are kept and the others are set to zero result would be:

 v1 v2 v3 v4 v5 
 4   0  3  4  3
 2   2  2  0  0
 0   10 0  0  0
 etc.

I tried something like this but it doesnt work (X is the dataframe):

X<- X[sweep(X, 1, rowMeans(X) < 0)] <- 0

Solution

  • One option could be:

    (df > rowMeans(df)) * df
    
      v1 v2 v3 v4 v5
    1  4  0  0  4  0
    2  2  2  2  0  0
    3  0 10  0  0  0