1

I want to do an analysis for each group in a row but it is a tedious way to filter each group.

My current data is like this after I have aggregate date data and group data to find the mean.

group.1 group.2 x
1.2.21 A 20
2.2.21 A 30
1.2.21 B 10
2.2.21 B 40

This is the ouput that i trying to do.

DATE A B
1.2.21 20 10
2.2.21 30 40

I have try using tapply but it is not the output that i want.

FrahChan04
  • 178
  • 1
  • 11
  • There are tons of ways. Look at `stats::reshape`, or `data.table::dcast` or other ways in the tidyverse. – nicola Apr 27 '21 at 07:07

1 Answers1

1

You could use pivot_wider from tidyr package

library(tidyr)
df %>% 
  pivot_wider(
    names_from = group.2,
    values_from = x
  ) %>% 
  rename(DATE = group.1)

Output:

  DATE       A     B
  <chr>  <int> <int>
1 1.2.21    20    10
2 2.2.21    30    40

data:

df <- tibble::tribble(
  ~group.1, ~group.2,  ~x,
  "1.2.21",      "A", 20L,
  "2.2.21",      "A", 30L,
  "1.2.21",      "B", 10L,
  "2.2.21",      "B", 40L
  )
TarJae
  • 72,363
  • 6
  • 19
  • 66