带嵌套条件的R ifelse语句

时间:2019-06-17 20:09:23

标签: r if-statement

x=data.frame("l"=c('a','b','d','a','c','c','d'),
             "t"=c(1:7))
x$l1 = ifelse(x$l=="a",1,
              ifelse(x$l=="b",2,
                     ifelse(x$l=="c",3,
                            ifelse(x$l=="d" ,4,
                                   ifelse(x$l=="d" & x$t==7,5,NA)))))

如您在最后一条语句上所见,如果l == "d" & t == 7,则l1应该等于5,但设置等于4。

3 个答案:

答案 0 :(得分:3)

public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.Add(new Route("K/{id}", new RedirectRouteHandler("K"))); routes.MapRoute( name: "K", url: "Home/K/{id}", defaults: new { controller = "Home", action = "K", id = UrlParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } 的执行会在它第一次命中ifelse时停止。

只需重新排序您的条件-

TRUE

还考虑使用x$l1 = ifelse(x$l=="a",1, ifelse(x$l=="b",2, ifelse(x$l=="c",3, ifelse(x$l=="d" & x$t==7,5, ifelse(x$l=="d" ,4,NA))))) x l t l1 1 a 1 1 2 b 2 2 3 d 3 4 4 a 4 1 5 c 5 3 6 c 6 3 7 d 7 5 包中的case_when();它将更具可读性。

答案 1 :(得分:2)

最好不要使用任何嵌套的ifelsecase_when。通过键/值数据集合并,可以轻松,高效地完成此任务

keydat <- data.frame(l = letters[1:4],l1 = 1:4)
left_join(x, keydat) %>%
     mutate(l1 = replace(l1, l== 'd' & t == 7, 5))
#  l t l1
#1 a 1  1
#2 b 2  2
#3 d 3  4
#4 a 4  1
#5 c 5  3
#6 c 6  3
#7 d 7  5

答案 2 :(得分:1)

根据@Shree的回答,这里是tidyverse版本:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

x <- data.frame("l"=c('a','b','d','a','c','c','d'),
             "t"=c(1:7))


x %>% 
  as_tibble() %>% 
  mutate(l1 = case_when(
    l == "a" ~ 1,
    l == "b" ~ 2,
    l == "c" ~ 3,
    l == "d" & t == 7 ~ 5,
    l == "d" ~ 4
  ))
#> # A tibble: 7 x 3
#>   l         t    l1
#>   <fct> <int> <dbl>
#> 1 a         1     1
#> 2 b         2     2
#> 3 d         3     4
#> 4 a         4     1
#> 5 c         5     3
#> 6 c         6     3
#> 7 d         7     5

reprex package(v0.3.0)于2019-06-17创建