0

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.

Cami
  • 35
  • 6
  • 1
    To help others, help you , `dput(head(my_dataframe, n = ?))` and replace your data.frame above by pasting `structure(....)` above, as your data.frame, as it makes helping easier. – Chris Aug 25 '23 at 22:19
  • 1
    Your codes for melt and pivot_wider refer to `spp` which is not a column in the example data. – Jon Spring Aug 25 '23 at 22:29
  • 1
    You mention what you want and what you tried, but we don't know what result you got (including any errors if applicable) and how that varied from what you wanted. – Jon Spring Aug 25 '23 at 22:29
  • 3
    Your pivot_wider code works fine for me if I use `species` instead of `spp` and remove the `values_fn = list` part. – Jon Spring Aug 25 '23 at 22:33

0 Answers0