Mostrando entradas con la etiqueta median. Mostrar todas las entradas
Mostrando entradas con la etiqueta median. Mostrar todas las entradas

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

    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

    2019-04-25

    Plot median and quartiles in ggplot2 using geom_pointrange

    Problem

    We would like to plot the interquartile range (IQR) and the median in ggplot2.

    Solution

    In this case we use the function geom_pointrange. We need to specify the interval (interquartile range) with the arguments fun.ymin and fun.ymax, and fun.y to plot the median.

    library(ggplot2)
    ggplot(data = diamonds) +
      geom_pointrange(mapping = aes(x = cut, y = depth),
                      stat = "summary",
                      fun.ymin = function(z) {quantile(z,0.25)},
                      fun.ymax = function(z) {quantile(z,0.75)},
                      fun.y = median)
    

    Results

    Related posts

    Spanish version

    References

    2018-02-01

    Representar cuartiles con geom_pointrange de ggplot2

    Problema

    Deseamos representar con una recta el rango intercuartílico marcando la mediana con un punto.

    Solución

    Empleamos la función geom_pointrange del paquete ggplot2. Delimitamos el min y máximo de y con fun.ymin y fun.ymax respectivamente. Con fun.y marcamos la coordinada del punto y para la mediana.

    library(ggplot2)
    ggplot(data = diamonds) +
      geom_pointrange(mapping = aes(x = cut, y = depth),
                      stat = "summary",
                      fun.ymin = function(z) {quantile(z,0.25)},
                      fun.ymax = function(z) {quantile(z,0.75)},
                      fun.y = median)
    

    Resultados

    Entradas relacionadas

    Referencias

    2016-03-12

    Calcular el mínimo y la mediana de cada fila en R

    Title

    Problema

    Queremos añadir al siguiente data frame dos columnas con el mínimo y la mediana de cada fila.

    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
    

    Solución

  • dplyr
  • library(dplyr)
    # Usando el operador %>%
    df %>% 
      rowwise() %>% 
      mutate(min= min(V1, V2, V3), median = median(c(V1, V2, V3)))
    # Sin el operador %>%
    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
    
  • Paquete 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
    

    Entradas relacionadas

    Referencias

    2015-10-17

    Substraer a cada valor de una fila la mediana de su respectiva fila en R

    Title

    Problema

    Queremos substraer a cada valor de una fila la mediana de la fila.

    Datos

    Creamos una matriz de 5x10.

    set.seed(24)
    m1 <- matrix(sample(0:9, 10*5, replace=TRUE), ncol=5)
    
          [,1] [,2] [,3] [,4] [,5]
     [1,]    2    6    0    3    4
     [2,]    2    3    5    2    3
     [3,]    7    6    7    3    2
     [4,]    5    6    1    1    2
     [5,]    6    3    2    9    0
     [6,]    9    9    6    2    0
     [7,]    2    1    0    7    3
     [8,]    7    0    5    6    3
     [9,]    8    5    6    6    2
    [10,]    2    1    0    9    3

    Solución

    m1 - apply(m1, 1, median)
    
          [,1] [,2] [,3] [,4] [,5]
     [1,]   -1    3   -3    0    1
     [2,]   -1    0    2   -1    0
     [3,]    1    0    1   -3   -4
     [4,]    3    4   -1   -1    0
     [5,]    3    0   -1    6   -3
     [6,]    3    3    0   -4   -6
     [7,]    0   -1   -2    5    1
     [8,]    2   -5    0    1   -2
     [9,]    2   -1    0    0   -4
    [10,]    0   -1   -2    7    1
    Si queremos conocer la mediana de cada fila.

    apply(m1, 1, median)
    
    [1] 3 3 6 2 3 6 2 5 6 2
    

    Notas

    Empleamos la función apply para aplicar una función a cada fila, en este caso la función median (mediana). En el segundo argumento de la función 1 indica que la función será aplicada sobre las filas (fila a fila). Las funciones apply son muy útiles en R pues evitan el uso de bucles (loops), pudiendo aplicar funciones a los márgenes, filas o columnas, de una matriz.

    Entradas relacionadas

    Referencias

    Nube de datos