简体   繁体   English

矩阵中的模拟和应用函数,R

[英]Simulation and apply functions in matrix, R

I have a couple of questions regarding to the piece of code shown below, the function called "Func1" will return a matrix as a result, the size of the matrix will be 50 rows and 15 columns, I called it "M", and "M2" is just the transpose of it.我有几个关于下面显示的代码段的问题,名为“Func1”的函数将返回一个矩阵作为结果,矩阵的大小将为 50 行和 15 列,我将其称为“M”,并且“M2”只是它的转置。 W0 is the initial value for the next part of the code, if I run the function called "Rowresult", then it also give me a 50*15 matrix. W0 是代码下一部分的初始值,如果我运行名为“Rowresult”的函数,那么它也会给我一个 50*15 的矩阵。

My first question is: if I want to run the "Rowresult" function for different W0 values,such as W0 = 10,20,30.我的第一个问题是:如果我想为不同的 W0 值运行“Rowresult”函数,例如 W0 = 10,20,30。 and I want to have 3 matrices in the size of 50*15 with different W0 values as results,how could I achieve it?我想有 3 个大小为 50*15 的矩阵,结果是不同的 W0 值,我该如何实现?

My second question is : if you tried my code in R, you will see a matrix called "wealth_result 2" as a result.我的第二个问题是:如果您在 R 中尝试我的代码,您将看到一个名为“wealth_result 2”的矩阵作为结果。 once I got this big matrix, I would like to divide it (50*15 matrix) into three same size matrix, each matrix has a size of 50*5 (so they share the same rows but different columns, the first matrix takes the first 5 columns, the second takes 6-10 columns, third one takes 11-15 columns),and then I want to work out how many positive rows (rows with all numbers positive) among each of the 50 *5 matrix?一旦我得到这个大矩阵,我想将它(50*15 矩阵)分成三个相同大小的矩阵,每个矩阵的大小为 50*5(因此它们共享相同的行但不同的列,第一个矩阵取前 5 列,第二列需要 6-10 列,第三个需要 11-15 列),然后我想算出每个 50 * 5 矩阵中有多少正行(所有数字都是正数的行)? How could I achieve this?我怎么能做到这一点?

N=15
func1<-function(N){
  alpha1 = 8.439e-02
  beta1 = 8.352e-01
  mu = 7.483e-03 
  omega = 1.343e-04
  X_0 = -3.092031e-02
  sigma_0 = 0.03573968
  eps = rt (N,7.433e+00)
  # loops
  Xn= numeric (N)
  sigma= numeric (N)
  sigma[1] = sigma_0
  Xn[1] = X_0
  for (t in 2:N){
    sigma[t] = sqrt (omega + alpha1 * (Xn[t-1])^2 + beta1* (sigma[t-1])^2)
    Xn[t] = sigma[t] * eps[t]
  }
  Y = mu + Xn
}

# return matrix 
M<-replicate(50,func1(N))

# returns matrix
M2<-t(M)
View(M2)

# wealth with initial wealth 10

W0=10
# 10,20,30,40
r= c(0.101309031, -0.035665516, -0.037377270, -0.005928941,  0.036612849,
0.062404039,  0.124240950, -0.034843633,  0.004770613,  0.005018101,
0.097685945, -0.090660099,  0.004863099,  0.029215984,  0.020835366)


Rowresult<- function(r){
  const = exp(cumsum(r))
  exp.cum = cumsum(1/const)
  wealth=const*(W0 - exp.cum)
  wealth 
  }

# wealth matrix
wealth_result <-apply(M2,1,Rowresult)
wealth_result2 <-t(wealth_result )
View(wealth_result2)

This delivers the desired counds of (all) "positive rows":这提供了所需的(所有)“正行”数:

> sapply(1:3, function(m) sum( rowSums( wealth_result2[ , (1:5)+(m-1)*5 ] >0 )) )
[1] 250 230   2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM