r - Empty data frame when computing ellipse data with vegan's ordiellipse for ggplot -
i trying group data points of nmds in ggplot adding ellipses using ordiellipse
function following helpful advice this post. however, although don't error messages or warnings, calculating ellipse data produces empty data frame. dataset available here, , code following:
library(vegan) library(ggplot2) setwd("c:") veg_matrix <- read.csv("161019_vegetation_matrix.csv",header=t); veg_matrix[2:123] <- lapply(veg_matrix[2:123],as.character); veg_matrix[2:123] <- lapply(veg_matrix[2:123],as.numeric) rownames(veg_matrix) <- veg_matrix[,1]; veg_matrix <- veg_matrix[,-1] # remove non-numeric rownames (=plot codes) dataset speciescomp_nmds = metamds(veg_matrix, k=2, trymax=100, distance="raup", na.rm=t) plot(speciescomp_nmds,display="sites",type="n") # add grouping data plot_scores <- as.data.frame(scores(speciescomp_nmds)) plot_scores$plot <- rownames(plot_scores);plot_scores <- cbind(plot_scores,data.frame(matrix(unlist(strsplit(plot_scores$plot,"_")),nrow=24,byrow=t)))[,-3]; colnames(plot_scores)[c(3,4)] <- c("summit","aspect") plot_scores$group <- "" plot_scores$group[plot_scores$summit=="buf"|plot_scores$summit=="ses"] <- "low" plot_scores$group[plot_scores$summit=="cha"|plot_scores$summit=="min"] <- "intermediate" plot_scores$group[plot_scores$summit=="cuo"|plot_scores$summit=="gaj"] <- "high" plot_scores$group <- transform(plot_scores, as.factor(plot_scores$group)) # compute ellipse data ord <- ordiellipse(speciescomp_nmds,plot_scores$group,display = "sites", kind = "sd", conf = .95, label=t) f_ellipse <- function (cov, center = c(0, 0), scale = 1, npoints = 100) { theta <- (0:npoints) * 2 * pi/npoints circle <- cbind(cos(theta), sin(theta)) t(center + scale * t(circle %*% chol(cov))) } df_ell_level <- data.frame() for(g in levels(plot_scores$group)){ if(is.null(ord[[g]])) next df_ell_level <- rbind(df_ell_level, cbind(as.data.frame(with(plot_scores[plot_scores$group==g,], f_ellipse(ord[[g]]$cov,ord[[g]]$center,ord[[g]]$scale))) ,level=group)) }
any ideas on how handle 1 warmly appreciated!
first convert group
factor
plot_scores <- transform(plot_scores, group = as.factor(group))
if fix loop be:
df_ell_level <- data.frame() for(g in levels(plot_scores$group)){ if(is.null(ord[[g]])) next df_ell_level <- rbind(df_ell_level, cbind(as.data.frame(f_ellipse(ord[[g]]$cov, ord[[g]]$center, ord[[g]]$scale)), level=g) ) }
then data frame 301 rows. i've cut out lot of unnecessary code call, , don't want rbind()
ing data frames in loop this.
Comments
Post a Comment