I am using vegan package to do some analysis and plots, like this
require(vegan)
data(varechem)
data(varespec)
rdam <- rda(varechem,scale=T)
scal=2
ef <- envfit(rdam ~ Cal.vul, data = varespec)
sf <- ordisurf(rdam ~ Cal.vul, data = varespec, plot = FALSE, scaling = scal)
plot(rdam, type="po",scaling = scal)
spe.sc <- scores(rdam, choices=1:2, display="sp",scaling = scal)
arrows(0, 0, spe.sc[, 1], spe.sc[, 2], length=0, lty=1, col="red")
ordilabel(rdam,dis="sp",cex=0.8,col="red",scaling = scal)
plot(ef)
plot(sf, col = "darkgreen", add = TRUE)
But I have to repeat the same plot changing only the variable Cal.vul so I would like to make a function:
plot_spcSurface <- function(rdam,speFram, speName, scal=2 )
{
ef <- envfit(rdam ~ speName, data = speFram)
sf <- ordisurf(rdam ~ speName, data = speFram, plot = FALSE, scaling = scal)
plot(rdam, type="po",scaling = scal)
spe.sc <- scores(rdam, choices=1:2, display="sp",scaling = scal)
arrows(0, 0, spe.sc[, 1], spe.sc[, 2], length=0, lty=1, col="red")
ordilabel(rdam,dis="sp",cex=0.8,col="red",scaling = scal)
plot(ef)
plot(sf, col = "darkgreen", add = TRUE)
}
plot_spcSurface(rdam,varespec,Cal.vul)
it gives
objeto 'Cal.vul' not found
if I call it like
plot_spcSurface(rdam,varespec,varespec$Cal.vul)
it works, but the name of the species is incorrect labelled "speName" instead of "Cal.vul" and I can't get the name from inside the function, what is the correct way to do this?
Thanks
Try this:
plot_spcSurface <- function(rdam,speFram, speName, scal=2 )
{
form <- as.formula(paste("rdam~",speName))
ef <- envfit(form, data = speFram)
sf <- ordisurf(form, data = speFram, plot = FALSE, scaling = scal)
plot(rdam, type="po",scaling = scal)
spe.sc <- scores(rdam, choices=1:2, display="sp",scaling = scal)
arrows(0, 0, spe.sc[, 1], spe.sc[, 2], length=0, lty=1, col="red")
ordilabel(rdam,dis="sp",cex=0.8,col="red",scaling = scal)
plot(ef)
plot(sf, col = "darkgreen", add = TRUE)
}
plot_spcSurface(rdam,varespec,"Cal.vul")
This passes the name of the predictor variable as a string and builds the formula internally.