Rearrange a dataframe into a matrix based on column values in R?

Viewed 93

I have a dataframe with three columns: values, type and class.

It looks like this:

df = data.frame(value = c(1:10), type = c("a","b","c","a","b","b","c","a","b","b"), 
                 class = c("aos","aos","ezx","ezx","kl","kl","wq","wq","us","us"))

    
value  type class
    1   a   aos
    2   b   aos
    3   c   ezx
    4   a   ezx
    5   b   kl
    6   b   kl
    7   c   wq
    8   a   wq
    9   b   us
    10  b   us


I want to rearrange it into a matrix where the columns represent the different type values and the rows the class values, and where the intersecting values are the mean value of the original data from the dataframe.

The matrix I am looking for should look like this:

   aos   ezx    kl   wq     us

a    1     4          8
b    2         5.5         9.5
c          3          7

1 Answers

We can use tapply from base R to return the structure

with(df, tapply(value, list(type, class), FUN = mean))
#  aos ezx  kl  us wq
#a   1   4  NA  NA  8
#b   2  NA 5.5 9.5 NA
#c  NA   3  NA  NA  7

Or with pivot_wider making use of values_fn

library(tidyr)
library(dplyr)
library(tibble)
df %>% 
  pivot_wider(names_from = class, values_from = value, values_fn = mean) %>% 
  column_to_rownames('type') %>%
   as.matrix
#  aos ezx  kl wq  us
#a   1   4  NA  8  NA
#b   2  NA 5.5 NA 9.5
#c  NA   3  NA  7  NA
Related