vegandevs / vegan

R package for community ecologists: popular ordination methods, ecological null models & diversity analysis
https://vegandevs.github.io/vegan/
GNU General Public License v2.0
448 stars 97 forks source link

Accessing NMDS points in metaMDS class object, with associated site names! #616

Closed gabrieltedone closed 8 months ago

gabrieltedone commented 8 months ago

Hi, thanks for vegan! And, sorry if this was already discussed about.

I find myself often in need to obtain the point values of the NMDS dimensions computed with the metaMDS function. When accessing points within a metaMDS class object either via metaMDS$points or scores(metaMDS)$points, a dataframe is returned, where columns are the NMDS dimensions computed and rows are... row numbers. As I understand it, each row corresponds to a specific site and the rows are ordered (top to bottom) in the same way as the input data was ordered (top to bottom).

The problem comes when I want to merge these points dataframes with other dataframes that might not have the same row order (top to bottom) that the metaMDS input data had. I find myself forced to bind dataframes using cbind which is row order dependent and is not exactly as "secure" as merging dataframes by sites, in this case, with the merge function.

It would be useful to have a way of accessing points with their associated sites in the same dataframe (i.e. sites as rownames).

jarioksa commented 8 months ago

The scores (points) will have row names if your data had row names:

> library(vegan)
> data(varespec)
> rownames(varespec)
 [1] "18" "15" "24" "27" "23" "19" "22" "16" "28" "13" "14" "20" "25" "7"  "5" 
[16] "6"  "3"  "4"  "2"  "9"  "12" "10" "11" "21"
> rownames(metaMDS(varespec, trace=FALSE)$points)
 [1] "18" "15" "24" "27" "23" "19" "22" "16" "28" "13" "14" "20" "25" "7"  "5" 
[16] "6"  "3"  "4"  "2"  "9"  "12" "10" "11" "21"
> rownames(scores(metaMDS(varespec, trace=FALSE), "sites"))
 [1] "18" "15" "24" "27" "23" "19" "22" "16" "28" "13" "14" "20" "25" "7"  "5" 
[16] "6"  "3"  "4"  "2"  "9"  "12" "10" "11" "21"

I guess you didn't have row names in your data.