X=c(5.3552,5.0212,11.1375,10.6883,0.0000,1.4795,0.0000,0.0000,0.8646,8.5751,4.8460,1.3602,20.3108,0.0000,20.883,0.000,0.000,11.3210,7.707,0.000)
Y=c(2.746,2.776,2.785,2.788,2.777,2.778,2.777,-2.0798,2.546,-1.3201,0.905,2.777,-11.7463,-0.2909,-0.2417,0.1206,2.7777,2.3524,1.7479,1.5524)
我将指标函数Z定义为:当X> 0时Z取1,当X = 0时取Z。 在这里,我无法为以下表达式
编写R代码(Z-1)*X+Z*Y
请帮助我解决这个问题。 谢谢。
答案 0 :(得分:0)
这个怎么样?
Z = rep(0, length(X))
Z[X>0] = 1
Z
#[1] 1 1 1 1 0 1 0 0 1 1 1 1 1 0 1 0 0 1 1 0
(Z-1)*X+Z*Y
#[1] 2.7460 2.7760 2.7850 2.7880 0.0000 2.7780 0.0000 0.0000 2.5460 -1.3201 0.9050 2.7770 -11.7463 0.0000 -0.2417 0.0000 0.0000
#[18] 2.3524 1.7479 0.0000
答案 1 :(得分:0)
您可以使用ifelse函数定义指标函数Z,其中Z在X> 0时取1并在X = 0时取0。
Z <- ifelse(X>0 , 1 , 0)
(Z-1)*X+Z*Y
[1] 2.7460 2.7760 2.7850 2.7880 0.0000 2.7780 0.0000 0.0000 2.5460 -1.3201 0.9050 2.7770 -11.7463 0.0000 -0.2417
[16] 0.0000 0.0000 2.3524 1.7479 0.0000