I want to rearrange my dataset by aggregating similar species and site, while converting them into a format like this below.
>
Species Value Site
A 1 D
A 2 D
B 3 E
B 4 E
C 1 F
C 2 F
into
>
Species D E F
A 3 1 0
B 0 7 0
C 0 0 3
Any help would be greatly appreciated. Sorry if the formatting is weird as this is my first time asking. Thank you in advance!
CodePudding user response:
- Try this
xtabs(Value ~ Species Site , data = df)
- Output
Site
Species D E F
A 3 0 0
B 0 7 0
C 0 0 3
CodePudding user response:
df %>%
group_by(Species, Site) %>%
summarise(sum = sum(Value)) %>%
pivot_wider(names_from = Site,
values_from = sum,
values_fill = 0)
# A tibble: 3 x 4
# Groups: Species [3]
Species D E F
<chr> <dbl> <dbl> <dbl>
1 A 3 0 0
2 B 0 7 0
3 C 0 0 3