我有这段代码:
val_hps_mix <- 0
co_neg_HP <- 1
co_pos_HP <- 2
e <- c(.1, -.2, 0, -.2)
if(val_hps_mix == 0 & co_neg_HP > 0 & co_pos_HP > 0) e[e < max(e[e < 0])] <- 0
if(val_hps_mix == 0 & co_neg_HP > 0 & co_pos_HP > 0) e[e < 0] <- e[e < 0]/length(e[e < 0])
e
正如所料,这会返回:
[1] 0.1 -0.1 0.0 -0.1
如何将IF放入函数中?以下不起作用,我没有得到预期的结果..
C.NAcc_hetero <- function(){
if(val_hps_mix == 0 & co_neg_HP > 0 & co_pos_HP > 0) e[e < max(e[e < 0])] <- 0
if(val_hps_mix == 0 & co_neg_HP > 0 & co_pos_HP > 0) e[e < 0] <- e[e < 0]/length(e[e < 0])
}
谢谢!
答案 0 :(得分:1)
您可以在功能中设置val_hps_mix
,co_neg_HP
和co_pos_HP
输入,如下所示:
e <- c(.1, -.2, 0, -.2)
C.NAcc_hetero <- function(val_hps_mix, co_neg_HP, co_pos_HP){
if(val_hps_mix == 0 & co_neg_HP > 0 & co_pos_HP > 0) e[e < max(e[e < 0])] <- 0
if(val_hps_mix == 0 & co_neg_HP > 0 & co_pos_HP > 0) e[e < 0] <- e[e < 0]/length(e[e < 0])
return(e)
}
然后使用这些输入运行该函数:
> C.NAcc_hetero(0, 1, 2)
[1] 0.1 -0.1 0.0 -0.1
使用此结构,C.NAcc_hetero
的输出将根据val_hps_mix
,co_neg_HP
和co_pos_HP
答案 1 :(得分:1)
试试这个。如您所见,没有默认参数,因此您可以根据需要更改和设置所有内容。
C.NAcc_hetero <- function(e, val_hps_mix, co_neg_HP, co_pos_HP){
if(val_hps_mix == 0 & co_neg_HP > 0 & co_pos_HP > 0) e[e < max(e[e < 0])] <- 0
if(val_hps_mix == 0 & co_neg_HP > 0 & co_pos_HP > 0) e[e < 0] <- e[e < 0]/length(e[e < 0])
e
}
C.NAcc_hetero(e=c(.1, -.2, 0, -.2), val_hps_mix=0, co_neg_HP=1, co_pos_HP=2)
[1] 0.1 -0.1 0.0 -0.1