Home > Back-end >  Add a column with the row median of certain columns
Add a column with the row median of certain columns

Time:08-26

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

CodePudding user response:

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)

CodePudding user response:

Try this one out

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

df$median = rowMedians(as.matrix(df[,c(2,3,4)]))
df
  •  Tags:  
  • r
  • Related