Hello!
I have this data frame that currently has species and density in column form, and I am trying to turn the data into a species by density matrix. Basically, I want all the species to be turned into column headers, and their densities to be in the rows, with "depth" being in column 1.
Here is an example of the dataframe:
structure(list(Species = c("Achnanthidium", "Actinastrum gracillimum",
"Actinastrum hantzschii", "Ankistrodesmus arcuatus"), Density = c(236.319,
3700, 5623.813, 53.24729)), class = "data.frame", row.names = c(NA,
-4L))
I want it to look like this, without having to manually do it for hundreds of rows:
structure(list(Depth = 0, Achnanthidium = 236.319, `Actinastrum gracillimum` = 3700,
`Actinastrum hantzschii` = 5623.813, `Ankistrodesmus arcuatus` = 53.24729), row.names = 1L, class = "data.frame")
Can anyone help?
Thank you so much!!!
FJCC
March 31, 2021, 8:10pm
2
What you want to do is basically a pivot_wider, as shown in the code below. What would determine the value of the Depth column?
DF <- structure(list(Species = c("Achnanthidium", "Actinastrum gracillimum",
"Actinastrum hantzschii", "Ankistrodesmus arcuatus"), Density = c(236.319,
3700, 5623.813, 53.24729)), class = "data.frame", row.names = c(NA,
-4L))
DF2 <- structure(list(Depth = 0, Achnanthidium = 236.319, `Actinastrum gracillimum` = 3700,
`Actinastrum hantzschii` = 5623.813, `Ankistrodesmus arcuatus` = 53.24729), row.names = 1L, class = "data.frame")
library(tidyr)
pivot_wider(DF, names_from = Species, values_from = Density)
#> # A tibble: 1 x 4
#> Achnanthidium `Actinastrum gracill~ `Actinastrum hantzsc~ `Ankistrodesmus arc~
#> <dbl> <dbl> <dbl> <dbl>
#> 1 236. 3700 5624. 53.2
Created on 2021-03-31 by the reprex package (v0.3.0)
1 Like
You are amazing! I had no idea it could be so simple. I forgot to include the Depth value in my original dataset, but amazingly, it did it for me with that code, exactly as I wanted.
Thank you, thank you, thank you, I can now start my NMDS analysis!!
system
Closed
April 7, 2021, 8:22pm
4
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.