组方差R

时间:2018-12-15 05:40:05

标签: r variance

我是R的新手,目前正在研究一个多元数据集,具体来说就是:http://archive.ics.uci.edu/ml/datasets/Wine

我在线找到了一个函数,用于计算组内差异和组间差异。我所指的网站就是这个网站:https://little-book-of-r-for-multivariate-analysis.readthedocs.io/en/latest/src/multivariateanalysis.html

当我继续时,组内方差的函数起作用,但是,当我尝试将函数用于组间方差时,出现此错误:警告消息: 在mean.default(variable)中:   参数不是数字或逻辑:返回NA

特定功能如下:

calcBetweenGroupsVariance <- function(variable,groupvariable) 


# find out how many values the group variable can take
{ groupvariable2 <- as.factor(groupvariable[[1]])
levels <- levels(groupvariable2)
# calculate the overall grand mean:
numlevel s <- length(levels)
grandmean <- mean(variable) 
# get the mean and standard deviation for each group:
numtotal <- 0
denomtotal <- 0
for (i in 1:numlevels)
      {
         leveli <- levels[i]
         levelidata <- variable[groupvariable==leveli,]
         levelilength <- length(levelidata)

         meani <- mean(levelidata)
         sdi <- sd(levelidata)
         numi <- levelilength * ((meani - grandmean)^2)
         denomi <- levelilength
         numtotal <- numtotal + numi
         denomtotal <- denomtotal + denomi 
      } 
      # calculate the between-groups variance
      Vb <- numtotal / (denomtotal - numlevels) 
      Vb <- Vb[[1]]
      return(Vb)
   }

对于解决此错误的任何帮助,将不胜感激。谢谢。

0 个答案:

没有答案