gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:32:19 25 4
gpt4 key购买 nike

我在 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)
}

这个函数通过让这两个输入生成一个带有一些随机数的向量 (2x50)。我想调用此函数 rand_x 1000 次并导出 1000 个矩阵,然后将结果绑定(bind)到最终矩阵中。我试图创建一个循环来解决这个问题,但我仍在努力。任何帮助将不胜感激。

最佳答案

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

尝试:

xRC <- rbind(
rowSums (Data [, c(18, 20)])
rowSums (Data [, c(19, 21)])
)

输出将是一个矩阵。

不过,我没有看到随机性出现在您的函数中的什么地方。如果您只想要一个带有随机数的 2x50 矩阵,您可能想要使用:

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

要执行此操作 1000 次,请尝试:

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)

关于r - 调用函数并在矩阵中提供输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47531897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com