I am trying to change a data frame from a long to wide format.
My data frame:
species site abundance
A 1 0
B 1 2
C 1 8
D 1 1
A 2 4
B 2 0
C 2 0
D 2 0
A 3 1
B 3 2
C 3 8
D 3 1
What I am trying to achieve is a species by site abundance data frame:
site A B C D
1 0 2 8 1
2 4 0 0 0
3 1 2 8 1
I have tried using the transpose function from base R, the melt and dcast functions from reshape2, and the pivot_wider function from tidyr:
t(my.df) #transpose
melt(my.df, id.vars = "site",
variable.name = "spp", value.name = "abundance") #rehsape2
dcast(my.df, "species" ~ "site", value.var = "abundance") #rehsape2
my.df %>%
pivot_wider(names_from = spp, values_from = abundance, values_fn = list) #tidyr
Im not sure if I am doing something wrong and I cannot find other functions to try. Any help is appreciated.