2020-06-24

Aplying a function by row in R

Title

Problem

We want to apply a function to each row of a data frame. In our example, we'd like to calculate the min and median for each row of a data frame.

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 pipe operator %>%
    df %>% 
      rowwise() %>% 
      mutate(min = min(V1, V2, V3), median = median(c(V1, V2, V3)))
    # Without %>%
    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 package
  • 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
    

    References

    No hay comentarios:

    Publicar un comentario

    Nube de datos