Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 调用函数并在矩阵中提供输出_R_Function_Matrix_Call - Fatal编程技术网

R 调用函数并在矩阵中提供输出

R 调用函数并在矩阵中提供输出,r,function,matrix,call,R,Function,Matrix,Call,我在R中有一个函数,我调用它 RS1 = t(cbind(Data[,18], Data[,20])) RS2 = t(cbind(Data[,19], Data[,21])) p = t(Data[23:24]) rand_x <- function (p, x) { n.goods <- dim (p)[1] n.obs <- dim (p)[2] xRC = NaN*matrix(1, n.goods, n.obs) for(i in 1:n.obs

我在R中有一个函数,我调用它

RS1 = t(cbind(Data[,18], Data[,20]))
RS2 = t(cbind(Data[,19], Data[,21]))
p = t(Data[23:24])

rand_x <- function (p, x) {
  n.goods <- dim (p)[1]
  n.obs   <- dim (p)[2]
  xRC = NaN*matrix(1, n.goods, n.obs)
  for(i in 1:n.obs) {
    xRC[1,i] <- RS1[1,i] + RS1[2,i]
    xRC[2,i] <- RS2[1,i] + RS2[2,i]
  }
  result <- xRC
  return(result)
}
RS1=t(cbind(数据[18],数据[20]))
RS2=t(cbind(数据[19],数据[21]))
p=t(数据[23:24])

rand_x如果要添加第18列到第20列的每个元素(这就是代码所做的),请尝试使用rowSums()

尝试:


xRC请发布您的循环代码和
xRC <- rbind(
  rowSums (Data [, c(18, 20)])
  rowSums (Data [, c(19, 21)])
)
xRC <- matrix (rnorm(50*2), 2)  # for standard-normal generated numbers
xRC <- matrix (sample(1:100, replace = T, size = 100), 2)  # for numbers between 1 and 100, uniformly distributed
for (i in 1:1000) {
  rbind(xRC,
    rowSums (Data [, c(18, 20)])
    rowSums (Data [, c(19, 21)])
  )
}
# or if you just want to generate random numbers, performance is way faster when you use:
xRC <- matrix(rnorm(1000 * 2 * 50), ncol = 50)