链接 ifelse 语句的智能方法? [英] Smart way to chain ifelse statements?

查看:29
本文介绍了链接 ifelse 语句的智能方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我必须链接 ifelse 语句时,它看起来像:

When I have to chain ifelse statements, it looks like:

ifelse(input=="x","x1",
       ifelse(input=="y","x2",
              ifelse(input=="z","x3",NA)))

有没有更聪明的方法来做到这一点?我正在考虑创建表然后合并或类似的东西只是为了让代码看起来更好?

Is there a smarter way to do this? I'm thinking about creating tables then merging or something alike just to make the code look better?

推荐答案

除了评论中的建议外,您还可以通过以下方式使用 match.

Apart from the suggestions in comments you could also use match in the following way.

创建示例数据:

set.seed(1)
vals_in <- c("x", "y", "z")   # unique values in your input vector
vec_in <- sample(vals_in, 10, replace = TRUE)  # sample from vals_in to create input
vals_out <-  c("x1", "x2", "x3")  # values to replace

现在,要替换嵌套的 ifelse ,您可以执行以下操作:

Now, to replace the nested ifelses you could do:

vec_out <- vals_out[match(vec_in, vals_in)]

结果是

vec_out
# [1] "x1" "x2" "x2" "x3" "x1" "x3" "x3" "x2" "x2" "x1"

<小时>

两种方法的比较:


A little comparison of two approaches:

set.seed(1)
vals_in <- letters
vec_in <- sample(vals_in, 1e7, replace = TRUE)
vals_out <-  LETTERS

system.time(vals_out[match(vec_in, vals_in)])
       User      System verstrichen 
      0.378       0.020       0.398 
system.time(unname(setNames(vals_out, vals_in)[vec_in]))
       User      System verstrichen 
      1.020       0.062       1.084 

这篇关于链接 ifelse 语句的智能方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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