使用Nas值最大化R中的函数

时间:2016-07-18 09:06:24

标签: r optimization na maximization

我想在代码中最大化funcToOpt

数据描述:

  1. wbX1是T x N矩阵,Nt是长度为N的向量
  2. wb的每一行的总和为1
  3. X1是横截面标准化的(平均值= 1 sd = 0)
  4. 标准化意味着theta*X1的横截面平均值为零,这意味着rowSums(wb + (theta1*X1) / Nt)始终为1。 当我使用没有NAs值的X1矩阵时,这种情况发生在我身上,是否有人知道在使用带有NA的矩阵时如何将wi的行和等于1? /强>

    最大化代码:

    X1 <- t(scale(t((X1))))    # X1 STANDARDIZATION
    N <- dim(X1)[2]
    T <- dim(X1)[1]
    
    M <- wb + r + X1                  # Nt, counting the NAs values
    Nt <- rowSums(!is.na(M)) 
    
    funcToOpt <- function (theta1)
    {
      inner <- rowSums((wb + (theta1*X1) / Nt) * r,na.rm = TRUE)  
    
      return (sum(inner, na.rm=TRUE) / T)
    }
    
    max<-optimize(funcToOpt, c(-50, 50), maximum = TRUE)
    
    theta1=max[[1]]                                 
    
    wi=wb+(theta1*X1) / Nt     
    rowSums(wi,na.rm=T)
    

    没有NA的MATRIX 5X5

    r=matrix(c(0.1,0.3,0.4,0.3,0.4,0.5,0.3,0.3,0.2,0.1,0.1,0.1,0.1,0.1,0.2,0.9,0.3,0.2,0.1,0.2,0.2,0.4,0.4,0.5,0.1),ncol = 5)
    wb=matrix(c(0.3,0.3,-0.4,-0.3,0.4,-0.5,-0.3,0.3,0.2,0.1,0.1,0.1,0.1,0.1,0.2,0.9,0.3,0.6,0.5,0.2,0.2,0.6,0.4,0.5,0.1),ncol = 5)
    X1=matrix(c(1:20,0,4,5,0,3),ncol = 5)
    

    MATRIX 5x5,NA

    r=matrix(c(0.1,0.3,0.4,0.3,0.4,0.5,0.3,0.3,0.2,0.1,0.1,0.1,0.1,0.1,0.2,0.9,0.3,0.2,0.1,0.2,0.2,0.4,0.4,0.5,0.1),ncol = 5)
    wb=matrix(c(0.3,0.3,-0.4,-0.3,0.4,-0.5,-0.3,0.3,0.2,0.1,0.1,0.1,0.1,0.1,0.2,0.9,0.3,0.6,0.5,0.2,0.2,0.6,0.4,0.5,0.1),ncol = 5)
    X1=matrix(c(1:20,NA,4,5,NA,3),ncol = 5)
    

0 个答案:

没有答案