Pergunta

based on Roland's suggestion from Plot titles in R using sapply(), I have created the following loop to make boxplots out of every selected variable in my dataset.

all.box=function(x) {
  for (i in seq_along(x)) {
    boxplot(x[,i], main = names(x)[i])
  }
}

It does the job nicely in that it provides the graphs. Could someone point out to me how to make the loop to return some output, say the $out from the boxplot to be able to see the number of outliers calculated by it?

Thanx a lot!

Foi útil?

Solução

Using lapply here is better to avoid side-effect of the for:

all.box=function(x) {
  res <- lapply(seq_along(x),function(i){
     boxplot(x[,i], main = names(x)[i])$out
  })
  res
}

PS: you can continue to use for, but you will need either to append a list as a result within your loop or to allocate memory for the output object before calling boxplot. So I think it is simpler to use xxapply family function here.

Outras dicas

If you want to return something from a for loop, it's very important to pre-allocate the return object if it's not a list. Otherwise for loops with many iterations will be slow. I suggest to read the R inferno and Circle 2 in particular.

all.box=function(x) {
  result <- list()
  for (i in seq_along(x)) {
    result[[i]] <- boxplot(x[,i], main = names(x)[i])$out
  }
  result
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top