2019-05-23

How to apply a function across rows in R

Problem

We'd like to apply a function across rows in R. In our example, we will add two columns calculating the minimum and the median for each row.

df <- structure(list(V1 = c(5L, 4L, 7L), V2 = c(8L, 9L, 3L), V3 = c(12L, 
5L, 9L)), .Names = c("V1", "V2", "V3"), class = "data.frame", row.names = c(NA, 
-3L))
 V1 V2 V3
1  5  8 12
2  4  9  5
3  7  3  9

Solution

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

    Source: local data frame [3 x 5]
    Groups: 
    
         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
    
  • Base R
  • df$min <- apply(df, 1, min) df$median <- apply(df[, 1:3], 1, median)

      V1 V2 V3 min median
    1  5  8 12   5      8
    2  4  9  5   4      5
    3  7  3  9   3      7
    

    Related posts

    References

    No hay comentarios:

    Publicar un comentario

    Nube de datos