Home > Software design >  In R, why is function "fviz_nbclust" not plotting when called inside a function?
In R, why is function "fviz_nbclust" not plotting when called inside a function?

Time:08-08

I am trying to run the function fviz_nbclust inside a function but it does not plot the graphic.

If I run in Debbug mode and press F10 on the fviz_nbclust line, it does not generate the graphic. But if I put the cursor on this line and press Ctrl Enter, the graphic shows up.

Any clues?

Main code:

library(factoextra)

df <- cbind(rnorm(100, mean = 0, sd = 1),rnorm(100, mean = 0, sd = 1))
df
run_cluster(df)

Function code:

run_cluster <- function(df){

  fviz_nbclust(df, 
               FUNcluster = kmeans, 
               method = "wss", 
               k.max = nrow(unique(df)) - 1, 
               nstart = 2)

    return (T)
}

CodePudding user response:

If you specifically print the plot it appears to work as expected; does this solve your problem?

library(factoextra)
#> Loading required package: ggplot2

df <- cbind(rnorm(100, mean = 0, sd = 1),rnorm(100, mean = 0, sd = 1))
head(df)
#>            [,1]       [,2]
#> [1,]  0.1046724 -1.2799086
#> [2,] -0.4395287 -0.8690895
#> [3,] -0.9810550 -1.1685272
#> [4,]  0.3313558  0.1799431
#> [5,]  0.3718252  2.5245255
#> [6,] -1.1644184  0.3907478

run_cluster <- function(df){
  
  kmeans_plot <- fviz_nbclust(df, 
               FUNcluster = kmeans, 
               method = "wss", 
               k.max = nrow(unique(df)) - 1, 
               nstart = 2)
  
  print(kmeans_plot)
}

run_cluster(df)

Created on 2022-08-08 by the reprex package (v2.0.1)

  • Related