[SOLVED] Function failed why?

Issue

file_1<-function(x)
  {
  x<-data.frame(x)
  for(i in 1:ncol(x))
    {
    if(class(x[ , i])=="character"){
      x<-factor(x[, i])
    }
  }
  par(mfrow=c(ceiling(ncol(x)/2),2))
  for(i in 1:ncol(x)){ 
    if(class(x[,i])=="factor")
      plot(x[, i], xlab=paste(colnames(x[i])))
  }
  else if(class(x[ ,i]=="numeric") {
    hist(x[ , i] , main=NULL, xlab=paste(colnames(x[, i])))
  }
}

}

x is a file, the function data.frames and factors the file and makes plots and histograms

Solution

You have braces and parens out of place. Namely,

  for(i in 1:ncol(x)){ 
    if(class(x[,i])=="factor")
      plot(x[, i], xlab=paste(colnames(x[i])))
  }
  else if(class(x[ ,i]=="numeric") {
    hist(x[ , i] , main=NULL, xlab=paste(colnames(x[, i])))
  }

The inner problem is that if(class(x[ ,i]=="numeric") should instead be if(class(x[ ,i])=="numeric").

The outer problem is that with your {...} braces, you are attempting for (...) { ... } else { ... }. I believe your else is meant to be inside the for loop, after the if.

Try this as a literal fix to the parsing errors.

file_1 <- function(x) {
  x <- data.frame(x)
  for (i in 1:ncol(x)) {
    if (class(x[ , i]) == "character"){
      x <- factor(x[, i])
    }
  }
  par(mfrow = c(ceiling(ncol(x)/2), 2))
  for (i in 1:ncol(x)){
    if (class(x[,i]) == "factor") {
      plot(x[, i], xlab = paste(colnames(x[i])))
    } else if (class(x[ ,i]) == "numeric") {
      hist(x[ , i] , main = NULL, xlab = paste(colnames(x[, i])))
    }
  }
}

Perhaps accept this altered version:

file_1 <- function(x) {
  ischr <- sapply(x, is.character)
  x[ischr] <- lapply(x[ischr], factor)
  par(mfrow = c(ceiling(ncol(x)/2), 2))
  for (i in seq_along(x)) {
    if (is.factor(x[,i])) {
      plot(x[,i], xlab = colnames(x)[i])
    } else {
      hist(x[,i], main = NULL, xlab = colnames(x)[i])
    }
  }
}

Answered By – r2evans

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.