Search code examples
rapplymediansapply

Calculationg median of observations in particular set of columns in R


I have an sf object containing the following columns of data:

HR60        HR70        HR80        HR90        HC60        HC70        HC80        HC90
0.000000    0.000000    8.855827    0.000000    0.0000000   0.0000000   0.3333333   0.0000000   
0.000000    0.000000    17.208742   15.885624   0.0000000   0.0000000   1.0000000   1.0000000   
1.863863    1.915158    3.450775    6.462453    0.3333333   0.3333333   1.0000000   2.0000000   
...

How can I calculate the median of HR60 to HR90 columns for all observations and place it in a different column, let's say HR-median? I tried to use apply(), but this kind of works for the whole dataset only and I need only these 4 columns to be considered.


Solution

  • We can select those columns

    df1$HR_median <- apply(subset(df1, select = HR60:HR90), 1, median)