Home > Mobile >  Use c() or as.vector() instead warning in R
Use c() or as.vector() instead warning in R

Time:09-27

Can anyone explain why I have following warning and how to fix it?

I cannot see why I have problems. It seems the final answer is correct.

#Creating variance and covariance matrix
c <- diag(0.5, nrow = 4)

c[lower.tri(c)] <- c(0.2, -0.3, 0.2, 0.5, -0.4, -0.7)

d <- c   t(c)

e <- c(10, 12, 5, 18)

f<- outer(e, e) * d

f
#Defining expected return
mu7 <- c(10, -15, -15, 13) 

#Define the value of lambda
labmda7 <- 0.8

#Define the benchmark portfolio weight
b7 <- c(0.2, 0.3, 0.4, 0.1)

#Solving alpha7
i <- c(1, 1, 1, 1)
alpha <- ( t(i) %*% solve(f) %*% mu7) / (t(i) %*% solve(f) %*% i)
xstar7 <- (1 / labmda7) * solve(f) %*% (mu7 - alpha * i )

warning:
Warning in alpha * i :
  Recycling array of length 1 in array-vector arithmetic is deprecated.
  Use c() or as.vector() instead.

CodePudding user response:

This warning is given because alpha is a matrix in your last line.

xstar7 <- (1 / labmda7) * solve(f) %*% (mu7 - as.vector(alpha) * i )

If you transform in a vector it will not an error.

CodePudding user response:

Note: Don't override R functions, like c. I renamed them for you.

You need to convert the arrays to vectors using as.vector.

Code:

x <- diag(0.5, nrow = 4)

x[lower.tri(x)] <- c(0.2, -0.3, 0.2, 0.5, -0.4, -0.7)

d <- x   t(x)

e <- c(10, 12, 5, 18)

f<- outer(e, e) * d

f
#Defining expected return
mu7 <- c(10, -15, -15, 13) 

#Define the value of lambda
labmda7 <- 0.8

#Define the benchmark portfolio weight
b7 <- c(0.2, 0.3, 0.4, 0.1)

#Solving alpha7
i <- c(1, 1, 1, 1)
alpha <- ( t(i) %*% solve(f) %*% mu7) / (t(i) %*% solve(f) %*% i)
alpha <- as.vector(alpha)
xstar7 <- (1 / labmda7) * solve(f) %*% (mu7 - alpha * i )

Or replace the last two lines with:

xstar7 <- (1 / labmda7) * solve(f) %*% (mu7 - as.vector(alpha) * i )

As you can see I write i <- as.vector(i) also alpha <- as.vector(alpha).

And now the output has no warning, output:

     [,1]  [,2] [,3]  [,4]
[1,]  100  24.0  -15  36.0
[2,]   24 144.0   30 -86.4
[3,]  -15  30.0   25 -63.0
[4,]   36 -86.4  -63 324.0
  • Related