samedi 25 novembre 2017

R Print function error

I am trying to write a function that takes a list of summary statistics, and prints the values in a nice format, see example below

example

   #Makes numbers to 4 decimal places
  formulate <- function(num){
   sprintf('%0.4f', num)
  }
  #Prints the value in a nice format
 print_stats <- function(lst){
 name <- names(lst)
 outcome <- c()
 for (i in 1:length(lst)){
  if (nchar(name[i])==max(nchar(names(lst)))){
  cat(name[i], ": ", formulate(lst[[i]]), "\n", sep = "")
  }
  else{
  cat(name[i], c(rep(" ", max(nchar(names(lst)))-
  nchar(name[i]))),
  ": ", formulate(lst[[i]]), "\n", sep = "")
   }
  }}

however, I keep getting the error

  Error in if (nchar(name[i]) == max(nchar(names(lst)))) { : 
  argument is of length zero
  In addition: Warning message:
   In max(nchar(names(lst))) : no non-missing arguments to max; returning -Inf

Aucun commentaire:

Enregistrer un commentaire