0

I'm trying to get the densities of numeric columns in a data frame and to assign them to new variables.

I'm using this function, but when I use it, it happens nothing. I'm kind of lost... Could you help me?

densities <- function(data.input, dense){
      for(i in 1:ncol(data.input)){
       if(is.numeric(data.input[,i]) == TRUE){
        dense <- density(data.input[, i])
        names(dense) <- paste(c("density"), colnames(data.input)[i], names(data.input), sep = ".")
        return(dense) ## I don't know how to make it return the created variable and have it in the environment
       }else{
         next
       }
       }
      }

Sorry if the answer is too obvious

  • 1
    That if() test will always be FALSE as currently written. Need to shift the inside closing parenthesis to come before the "==". It's also superfluous to further test an `is.` function with `==TRUE`, so stop shooting your code in the feet. You also need to stop overwriting values within loops. – IRTFM Dec 02 '14 at 22:20
  • 1
    Also, the way to have this written, the function will return after processing the first numeric column. – jlhoward Dec 02 '14 at 22:33
  • 1
    The object `density` will get replaced every time through the loop and you will only get a single result which will be the last assignment. – IRTFM Dec 02 '14 at 23:46

1 Answers1

2

Does this work for you?

results <- apply(data.input, 2, density)

I just noticed that maybe you have some non-numeric columns, this should work in that case:

results <- apply(data.input[sapply(data.input, is.numeric)], 2, density)
Nick DiQuattro
  • 729
  • 4
  • 7