#Example of calculating goodness of fit #for MDS via cmdscale() #Written by Michael R.W. Dawson, spring of 2015 #Basic idea: Do MDS on distance data with cmdscale. Use the coordinates #from this solution to recreate the distances. String the original #distances and the new distances matrices out into two columns. #Calculate the correlation between these two columns. Square this #correlation to get proportion of variance accounted for. #Compute degrees of freedom = df = n -2 where n = length of a strung out matrix #Compute F = (rsquared/1)/((1 - rsquared)/df) #Evaluate p value for F at 1,df degrees of freedom #This example is based uses the eurodist dataset, which is already a set of distances #The distances between 21 European cities, standard dataset in R eurodist #display the starting distance data # Perform MDS on the data using cmdscale; k determines the number of dimensions EuroMDS <- cmdscale(eurodist, eig=TRUE, k=2) # ---- Code below calculates goodness of fit ---- # Copy coordinates from MDS into a new matrix NewEuroCoords = EuroMDS$points #take coords from cmdscale solution #Compute a new set of distances from the MDS coordinates delivered by cmdscale NewEuroDists <- dist(NewEuroCoords, diag=TRUE, upper=TRUE) #String the two distance matrices out into two columns #and calculate the correlation between these two columns r <- cor(c(eurodist), c(NewEuroDists)) #compute and display r squared from this correlation, this is variance accounted for rsquared <- r * r #compute rsquared #display #compute F test on this correlation #degrees of freedom for numerator = 1 #compute degrees of freedom for denominator = N - 2 and display freedom = NROW(c(NewEuroDists)) - 2 freedom #display df for denominator #compute and display F Fvalue <- rsquared /((1 - rsquared)/freedom) #compute Fvalue #display #use pf to determine the p-value of this F at df = 1, freedom pf(Fvalue, 1, freedom, lower.tail=FALSE) #End result: goodness of fit measured as ability to #reconstruct original distances, along with #a significance test of this ability