智能方式链接ifelse语句?

Seb*_*ian 6 if-statement r

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

ifelse(input=="x","x1",
       ifelse(input=="y","x2",
              ifelse(input=="z","x3",NA)))
Run Code Online (Sandbox Code Playgroud)

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

tal*_*lat 11

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

创建样本数据:

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
Run Code Online (Sandbox Code Playgroud)

现在,要替换嵌套的ifelses,你可以做:

vec_out <- vals_out[match(vec_in, vals_in)]
Run Code Online (Sandbox Code Playgroud)

结果是

vec_out
# [1] "x1" "x2" "x2" "x3" "x1" "x3" "x3" "x2" "x2" "x1"
Run Code Online (Sandbox Code Playgroud)

两种方法的一点比较:

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 
Run Code Online (Sandbox Code Playgroud)


RHe*_*tel 8

您可以尝试这样的功能:

choice <- function(input) {
  switch(input,
         "x"="x1",
         "y"="x2",
         "z"="x3",
         NA)
}
#> choice("x")
#[1] "x1"
#> choice("z")
#[1] "x3"
#> choice("other")
#[1] NA
Run Code Online (Sandbox Code Playgroud)


akr*_*run 5

另一种选择是使用 setNames

unname(setNames(vals_out, vals_in)[vec_in])
#[1] "x1" "x2" "x2" "x3" "x1" "x3" "x3" "x2" "x2" "x1"
Run Code Online (Sandbox Code Playgroud)

注意:从@docendo discimus post中获取示例.