问题
I have a data frame (data) with 53 columns (ID column plus 52 numeric values). I can add a column with mean with the following:
data$mean <- rowMeans(data[,2:51],na.rm = TRUE) # add mean of rows
But, I cannot do the same for median with the following:
data$medians <- rowMedians(month.sum[,2:51],na.rm = TRUE) # add medians of rows
I installed the package matrixStats which includes rowMedians
, but it does not work for me.
回答1:
You can apply arbitrary functions to rows with apply
. Use
apply(data[,2:51],1, median, na.rm = TRUE)
Read the ?apply
help page for more information.
来源:https://stackoverflow.com/questions/28077887/how-to-add-median-value-to-rows