测试数据及其确定方法位于:Use of IF function in R
我需要将'Test'数据输入另一个函数。下面提供了x和y的数据(基本上是两个选项,1 =(89.3,12.1)和2 =(97.2,8.5)。下面的等式是更大函数的一部分,但这就是问题所在。我想要什么要做的是从我们的矢量(测试)中单独调用每个值,并且输出对于测试中的每个值都有2个值。当我直接链接测试时,我会收到一个具有50个输出值的新向量,这使得没有真正的意义。如果我把测试向量中的第一个值放入,我会收到2个值正确的输出(我已手动检查过)。
set.seed(1)
Test <- ifelse(runif(50, 0, 1) < 0.69, rnorm(50, 25, 4), rnorm(50, 28, 4.3))
x <- c(89.3, 97.2)
y <- c(12.1, 8.5)
c(-0.75*(((Test)-x)/y)^2)
输出目前来自上述函数:
[1] -21.32750 -55.05068 -25.23216 -49.25087 -20.09236 -53.28421 -19.61593
[8] -51.81307 -21.32136 -62.68412 -22.28700 -56.50245 -21.33593 -47.71792
[15] -18.53459 -55.10348 -16.12545 -42.79888 -19.73790 -40.38937 -17.77048
[22] -51.94862 -19.20262 -54.78823 -18.92120 -51.75187 -22.82277 -52.08655
[29] -18.82475 -45.86141 -16.28231 -56.33673 -24.02006 -50.75048 -14.97440
[36] -40.67076 -20.51602 -50.05597 -21.04648 -58.66084 -20.32455 -65.47588
[43] -20.01028 -53.19754 -15.84125 -52.88386 -23.09141 -50.51265 -19.73710
[50] -50.32994
但从测试中获取第一个值并手动将其放入:
c(-0.75*(((24.77549)-x)/y)^2)
[1] -21.32750 -54.44958
这是我想要的所有50个测试值
感谢您的帮助。
答案 0 :(得分:2)
使用sapply:
set.seed(1)
Test <- ifelse(runif(50, 0, 1) < 0.69, rnorm(50, 25, 4), rnorm(50, 28, 4.3))
x <- c(89.3, 97.2)
y <- c(12.1, 8.5)
result = sapply(Test, function(t) c(-0.75*(((t)-x)/y)^2))
result
则为2x50矩阵:
> result
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] -21.32750 -21.59186 -25.23216 -19.04891 -20.09236 -20.81548 -19.61593
[2,] -54.44959 -55.05068 -63.29020 -49.25087 -51.63562 -53.28421 -50.54767
[,8] [,9] [,10] [,11] [,12] [,13] [,14]
[1,] -20.17012 -21.32136 -24.96341 -22.28700 -22.23106 -21.33593 -18.37988
[2,] -51.81307 -54.43561 -62.68412 -56.62937 -56.50245 -54.46874 -47.71792
[,15] [,16] [,17] [,18] [,19] [,20] [,21]
[1,] -18.53459 -21.61509 -16.12545 -16.24298 -19.73790 -15.20235 -17.77048
[2,] -48.07270 -55.10348 -42.52723 -42.79888 -50.82633 -40.38937 -46.31876
[,22] [,23] [,24] [,25] [,26] [,27] [,28]
[1,] -20.22954 -19.20262 -21.47642 -18.92120 -20.14330 -22.82277 -20.29001
[2,] -51.94862 -49.60262 -54.78823 -48.95848 -51.75187 -57.84436 -52.08655
[,29] [,30] [,31] [,32] [,33] [,34] [,35]
[1,] -18.82475 -17.57154 -16.28231 -22.15805 -24.02006 -19.70470 -14.97440
[2,] -48.73760 -45.86141 -42.88975 -56.33673 -60.55407 -50.75048 -39.86019
[,36] [,37] [,38] [,39] [,40] [,41] [,42]
[1,] -15.32366 -20.51602 -19.40083 -21.04648 -23.18320 -20.32455 -26.20255
[2,] -40.67076 -52.60188 -50.05597 -53.81015 -58.66084 -52.16534 -65.47588
[,43] [,44] [,45] [,46] [,47] [,48] [,49]
[1,] -20.01028 -20.77743 -15.84125 -20.63975 -23.09141 -19.60061 -19.7371
[2,] -51.44830 -53.19754 -41.86986 -52.88386 -58.45297 -50.51265 -50.8245
[,50]
[1,] -19.52067
[2,] -50.32994