Function call and Ctrl+Enter execution give different output in R

Viewed 24

I have a main.R script in which I make this call:

ds <- eda(ds)

where, the eda function is this:

eda <- function(ds){
  log4r.info(eda_logger, "Prepping data")
  ds <- prep.data(ds)
  
  log4r.info(eda_logger, "Feature selection")
  ds <- feature.selection(ds)
  
  log4r.info(eda_logger, "Univariate Descriptive Statistics Graph")
  univariate.descriptive.statistics.graph(ds)
  
  return(ds)
}

which calls the univariate.descriptive.statistics.graph function:

univariate.descriptive.statistics.graph <- function(ds){
  # Density
  out_density_path <- paste0(out_graph, "/density_age.svg") #line 1
  svg(out_density_path)  #line 2
  lattice::densityplot(ds$age, xlab="Age")  #line 3
  dev.off()  #line 4
}

Now when I look into the output folder of the density plot I get a completely blank density_age.svg.

But, If I now go onto line1 and press Ctrl+Enter and then again for line2, line3 and line4, I get a density_age.svg with inside the plot.

And I'm sure the ds dataframe its executing on its the same because the code runs to completion (doesn't give any error) and I reassign it to the ds variable (first line of code above).

EDIT:

> dput(head(ds, 20)) 

structure(list(gender = structure(c(2L, 1L, 2L, 1L, 1L, 2L, 2L, 
1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 2L), .Label = c("Female", 
"Male", "Other"), class = "factor"), age = c(67, 61, 80, 49, 
79, 81, 74, 69, 59, 78, 81, 61, 54, 78, 79, 50, 64, 75, 60, 57
), hypertension = c(0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 1L, 
0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L), heart_disease = c(1L, 0L, 
1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 0L, 
0L, 1L), avg_glucose_level = c(228.69, 202.21, 105.92, 171.23, 
174.12, 186.21, 70.09, 94.39, 76.15, 58.57, 80.43, 120.46, 104.51, 
219.84, 214.09, 167.41, 191.61, 221.29, 89.22, 217.08), bmi = c(36.6, 
NA, 32.5, 34.4, 24, 29, 27.4, 22.8, NA, 24.2, 29.7, 36.8, 27.3, 
NA, 28.2, 30.9, 37.5, 25.8, 37.8, NA), smoking_status = structure(c(1L, 
2L, 2L, 3L, 2L, 1L, 2L, 2L, NA, NA, 2L, 3L, 3L, NA, 2L, 2L, 3L, 
3L, 2L, NA), .Label = c("formerly smoked", "never smoked", "smokes"
), class = "factor"), stroke = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), row.names = c(NA, 
20L), class = "data.frame")
0 Answers
Related