比R中的ifelse()函数更快 [英] Faster function than an ifelse() in r
问题描述
我有3列标记,得分,阶段.
标记的值为1或0,分数将为大于0的任何值.我们需要计算阶段值.
Flag will have values 1 or 0, Score will be any values above 0. We need to calculate stage values.
所以我们的数据(stagedata)看起来像这样:
so our data (stagedata) will look like this:
Flag Score Stage
1 35
1 0
0 12
....
如果标志== 1且得分> = 30,我们将阶段计算为2,
IF Flag == 1 and score >= 30, the we calculate stage as 2,
,如果Flag == 0或Flag == 1且得分< 30,阶段= 1.
and if Flag ==0 or Flag == 1 and score < 30, stage = 1.
任何其他案例阶段都将被计算为0(即,由于输入中的某些错误或缺少分数或标志).
Any other case stage will be calculated as 0 (ie, due to some error in input or if score or flag is missing).
stagedata$Stage <- ifelse(stagedata$Flag==1,ifelse((stagedata$Score>=30),2,1),ifelse(stagedata$Flag==0,1,0))
stagedata$Stage[is.na(stagedata$Stage)] <-0
是否有其他更有效的方法(例如套用)来执行此操作?我们正在处理的数据大约为10 thunsands
推荐答案
我们可以通过一些算术运算将逻辑向量转换为整数
We can convert the logical vector to integer with some arithmetic operation
v1 <- with(stagedata, 2 *(Flag == 1 & score >= 30) + (Flag %in% 0:1 & score <30))
v1
#[1] 2 1 1 2 1 0
如果有NA值,则将其替换为0
If there are NA values, then replace it with 0
v1[is.na(v1)] <- 0
数据
stagedata <- data.frame(Flag = c(1, 1, 0, 1, 0, 2), score = c(35, 0, 12, 31, 27, 31))
这篇关于比R中的ifelse()函数更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!