缩短嵌套ifelse [英] Shorten nested ifelse

查看:70
本文介绍了缩短嵌套ifelse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果给出了以下数据表,因此我们希望将x1与x2和x5进行比较,则可以使用以下内容:

If the following data table is given, and we would like to compare x1 consequently with x2 to x5, the following can be used:

set.seed(1)
library(data.table)
TDT <- data.table(x1 = round(rnorm(100,0.75,0.3),2),
                  x2 = round(rnorm(100,0.75,0.3),2),
                  x3 = round(rnorm(100,0.75,0.3),2),
                  x4 = round(rnorm(100,0.75,0.3),2),
                  x5 = round(rnorm(100,0.75,0.3),2))

TDT[,compare := ifelse(x1 < x2,1,ifelse(x1 < x3,2,ifelse(x1 < x4,3,ifelse(x1 < x5,4,5))))]

因此,如果 x1< x2 ,然后 compare == 1 ,依此类推。

So if x1 < x2, then compare == 1, etc.

在我的示例中,我有很多专栏可以比较x1。有什么方法可以更简洁地编写此代码,即没有嵌套的ifelse吗?

Now in my example, I have a lot more columns to compare x1 with. Is there any way to write this more concisely, i.e. without nested ifelse?

推荐答案

我们可以使用 data.table

TDT[, compare := {d1 <- as.data.table(Map(function(x) x1 < x, .SD))
       max.col(d1, "first") *(c(5, 1)[((Reduce(`+`, d1)!=0)+1)])}, .SDcols = x2:x5]

#OP's code
v1 <- TDT[, ifelse(x1 < x2,1,ifelse(x1 < x3,2,ifelse(x1 < x4,3,ifelse(x1 < x5,4,5))))]
identical(v1, TDT$compare)
#[1] TRUE

这篇关于缩短嵌套ifelse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆