NewUsr_stat
NewUsr_stat

Reputation: 2583

Conditional row-wise average

I have a simple question. I have a data.frame that looks like this:

df

 A             B             C         Exclusion_criteria
 3             4             5                 3      
 2                                             1     
 6             9                               2       

I simply would like to mean rows of columns A, B and C (row-wise) when the Exclusion_criteria is different from 1 (e.g. for all cases except Exclusion_criteria == 1).

Can anyone help me please?

Kind regards

Upvotes: 0

Views: 168

Answers (1)

akrun
akrun

Reputation: 887213

We can loop over the rows with apply, remove the element that is showed in the 4th column by, and get the mean

apply(df, 1, function(x) mean(x[1:3][-x[4]], na.rm = TRUE))
#[1] 3.5 NaN 6.0

Or another option is to replace the values in 'df' based on the row/column index (from 4th column) to NA and do a rowMeans

df[cbind(1:nrow(df), df[,4])] <- NA
rowMeans(df[1:3], na.rm = TRUE)
#[1] 3.5 NaN 6.0

Upvotes: 1

Related Questions