在R中使用函数获得数据框中数字列的密度。

问题描述 投票:0回答:1

我试图获得数据框架中数字列的密度,并将它们分配给新的变量。

我正在使用这个函数,但当我使用它时,什么都没有发生。我有点迷茫... 你能帮助我吗?

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
       }
       }
      }

如果答案太明显,抱歉

r for-loop environment-variables probability-density
1个回答
2
投票

这对你有用吗?

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

我只是注意到,也许你有一些非数字列,在这种情况下,这应该工作。

results <- apply(data.input[sapply(data.input, is.numeric)], 2, density)
© www.soinside.com 2019 - 2024. All rights reserved.