alex
alex

Reputation: 844

Add a column with the row median of certain columns

I have the following

col1  col2  col3   col4   col5    
1      2     1      5      5      
3      7     3      1      3      
5      8     9      2      5      


I want to add a column that calculates the row median, but only for certain columns (eg. 2-4)


col1  col2  col3   col4   col5   median 
1      2     1      5      5       2
3      7     3      1      3       3
5      8     9      2      5       8

Upvotes: 0

Views: 208

Answers (2)

amanwebb
amanwebb

Reputation: 380

Try this one out

install.packages("matrixStats")
library(matrixStats)

df$median = rowMedians(as.matrix(df[,c(2,3,4)]))
df

Upvotes: 1

Brutalroot
Brutalroot

Reputation: 311

df <- data.frame(col1 = c(1,3,5), col2 = c(2,7,8), col3 = c(1,3,9), col4 = c(5,1,2), col5 = c(5,3,5))

df$median <- apply(df[,2:4], 1, median, na.rm=T)

Upvotes: 2

Related Questions