Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Min and Median of Multiple Columns of a DF by Row in R

Tags:

r

Given a dataframe that looks like:

V1  V2  V3
5   8   12
4   9   5
7   3   9
...

How to add columns to the dataframe for min and median of these 3 columns, calculated for each row?

The resulting DF should look like:

V1  V2  V3  Min  Median
5   8   12  5    8
4   9   5   4    5
7   3   9   3    7
...

I tried using dplyr::mutate:

mutate(df, Min = min(V1,V2,V3)) 

but that takes the min of the entire dataframe and puts that value in every row. How can I get the min and median of just each row?

For Mean, I can use rowMeans in mutate, but there are no similar functions for min and median.

Also tried,

lapply(df[1:3], median)

but it just produces the median of each column

dd <- read.table(header = TRUE, text = 'V1  V2  V3
5   8   12
4   9   5
7   3   9')
like image 920
brno792 Avatar asked Dec 07 '22 23:12

brno792


1 Answers

With dplyr, using the function rowwise

library(dplyr)
mutate(rowwise(df), min = min(V1, V2, V3), median = median(c(V1, V2, V3)))
# Using the pipe operator %>%
df %>% 
  rowwise() %>% 
  mutate(min= min(V1, V2, V3), median = median(c(V1, V2, V3)))

Output:

Source: local data frame [3 x 5]
Groups: <by row>

     V1    V2    V3   min median
  (int) (int) (int) (int)  (int)
1     5     8    12     5      8
2     4     9     5     4      5
3     7     3     9     3      7
like image 159
mpalanco Avatar answered Jan 05 '23 01:01

mpalanco