Home > OS >  Table in R showing mean values from dataframe
Table in R showing mean values from dataframe

Time:02-23

I have a data set that is formatted similar to this:

A | B | C
---------
0 | 1 | 2
0 | 2 | 3
1 | 5 | 9
1 | 2 | 11
2 | 6 | 7
2 | 3 | 4
3 | 8 | 10

The data is in a dataframe and I'm currently looking to create a table that shows the mean of B and C for each unique value of A.

The resulting table would look something like this:

A |       B       |      C
--------------------------------
0 | mean(B for 0) | mean(C for 0)
1 | mean(B for 1) | mean(C for 1)
2 | mean(B for 2) | mean(C for 2)
etc

Is there a function that can do this in R? Or is there a different recommended way?

CodePudding user response:

library(dplyr)

df |>
    group_by(a) |>
    summarize(across(everything(), mean))

  # A tibble: 4 × 3
      a     b     c
  <dbl> <dbl> <dbl>
1     0   1.5   2.5
2     1   3.5  10  
3     2   4.5   5.5
4     3   8    10  
  •  Tags:  
  • r
  • Related