Search code examples
rtibble

How calculate average values for lists in R tibble?


Let say I have R tibble

  df <- tibble(
    name = c("x", "y"),
    prob = list(c(1,2,3), c(4,5,6))
  )

How calculate average of values for "prob" field.

Expected result is a list with values c((1+4)/2, (2+5)/2, (3+6)/2) => c(2.5, 3.5, 4.5)


Solution

  • Use Reduce to get element-wise addition and divide it by number of rows in the dataframe.

    Reduce(`+`, df$prob)/nrow(df)
    #[1] 2.5 3.5 4.5
    

    Other alternatives with rowMeans and colMeans.

    colMeans(do.call(rbind, df$prob))
    rowMeans(do.call(cbind, df$prob))