pcaMethods icon indicating copy to clipboard operation
pcaMethods copied to clipboard

slplot fails if called inside a function

Open StuntsPT opened this issue 5 years ago • 1 comments

Dear pcaMethods team,

While teaching a class last week we have realized that slplot will fail if called from inside a function with the error:

Error in plot.xy(xy, type, ...) : object '<object_name used as argument for "scol">' not found 

I'm not sure this is a bug in pcaMethods or something more general to R. But I thought I should provide you with a 'heads up' nontheless.

Below is a minimal example you can use for reproducing the issue:

library(pcaMethods)

wine <- read.csv("http://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data", sep=",")

# Add column names
colnames(wine) <- c("Cultivar", "Alcohol", "Malic acid", "Ash",
                    "Alcalinity of ash", "Magnesium", "Total phenols",
                    "Flavanoids", "Nonflavanoid phenols", "Proanthocyanins",
                    "Color intensity", "Hue", "OD280/OD315 of diluted wines",
                    "Proline")

# The first column corresponds to the cultivar class
cultivar_classes <- factor(wine[,"Cultivar"])

winePCAmethods = pca(wine[,-1], scale="vector", center=T, nPcs=2, method="svd")

# Plot it
slplot(winePCAmethods,
       scol=cultivar_classes,
       scoresLoadings=c(TRUE,FALSE))

legend("bottomright", legend = c("Cv1","Cv2","Cv3"), pch = 1,
       col = c("black","red","green"))

slplot(winePCAmethods,
       scoresLoadings=c(FALSE,TRUE))

### The above part works just fine. Below is where the problem lies:

my_broken_function = function(current_data, current_classes) {
  
  my_PCAmethods = pca(current_data[,-1], scale="vector", center=T, nPcs=2, method="svd")
  
  # Plot it
  slplot(my_PCAmethods,
         scol=current_classes,
         scoresLoadings=c(TRUE,FALSE))
  
  legend("bottomright", legend = c("Cv1","Cv2","Cv3"), pch = 1,
         col = c("black","red","green"))
}

my_broken_function(wine, cultivar_classes)

In short, if slplot is called from inside a function, the argument for scol cannot be found.

We thought it would be helpful to report. If any further information is required, feel free to ask away.

StuntsPT avatar Nov 15 '20 21:11 StuntsPT

Hi, Thanks for the info and excellent bug report, slplot was mainly meant as a quick way to plot results in an interactive session. But that's no excuse for the inelegant failure. I'll have a look.

hredestig avatar Nov 16 '20 15:11 hredestig