巧妙地链接ifelse陈述?

时间:2016-02-11 10:20:01

标签: r if-statement

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

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

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

3 个答案:

答案 0 :(得分: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

现在,要替换您可以执行的嵌套ifelse

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

结果是

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

两种方法的比较:

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 

答案 1 :(得分:8)

您可以尝试这样的功能:

select state, product, column_3, column_4
from (
  select state, product, column_3, column_4, 
         count(*) over (partition by state) as cnt
  from the_table
) t
where cnt > 1;

答案 2 :(得分:5)

另一种选择是使用setNames

unname(setNames(vals_out, vals_in)[vec_in])
#[1] "x1" "x2" "x2" "x3" "x1" "x3" "x3" "x2" "x2" "x1"

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