R语言【dplyr】——case_when()是一般向量化的 if-else(),该函数允许您将多个 if_else() 语句矢量化

Package dplyr version 1.1.4


Parameters

case_when(..., .default = NULL, .ptype = NULL, .size = NULL)

参数【...】<dynamic-dots> 一组两面公式(two-sided formulas)。

  • 公式左边(left hand side,LHS)决定了哪些值符合这种情况。
  • 公式右边(right hand side,RHS)提供了替换值。
  • LHS 输入的结果必须是逻辑向量。
  • RHS 输入将被强制转换为通用类型。
  • 所有输入的数据都将被回收利用,恢复到其平常大小。尽管如此,我们还是鼓励所有 LHS 输入的大小相同。
  • 循环主要适用于 RHS 输入,在这种情况下,您可能会提供一个大小为 1 的输入,它将被循环为 LHS 输入的大小。
  • 输入 NULL 将被忽略。

参数【.default】:当所有 LHS 输入返回 FALSE NA 时使用的值。

  • 参数【.default】的大小必须为 1 或与参数【...】计算出的通用大小相同。
  • 参数【.default】与 RHS 输入一起参与通用类型的计算。
  • LHS 条件中的 NA 值将被视为 FALSE,这意味着这些位置的结果将被分配为参数【.default】值。要以不同的方式处理条件中的缺失值,必须在它们落入参数【.default】之前明确地用另一个条件来捕获它们。这通常涉及 is.na(x) ~ value 的一些变体,以适应您对 case_when() 的使用。
  • 如果为 NULL(默认值),将使用缺失值。

参数【.ptype】:一个可选的原型,用于声明所需的输出类型。如果提供,将覆盖 RHS 输入的通用类型。

参数【.size】:一个可选的大小,用于声明所需的输出大小。如果提供,它将覆盖从参数【...】计算出的通用大小。


Value

一个向量,其大小与参数【...】中输入值计算出的共同大小相同,类型与参数【...】中 RHS 输入值的共同类型相同。


Examples

1. 最简单的例子

x <- 1:70
case_when(x %% 35 == 0 ~ "fizz buzz",x %% 5 == 0 ~ "fizz",x %% 7 == 0 ~ "buzz",.default = as.character(x)
)
 [1] "1"         "2"         "3"         "4"         "fizz"      "6"        [7] "buzz"      "8"         "9"         "fizz"      "11"        "12"       
[13] "13"        "buzz"      "fizz"      "16"        "17"        "18"       
[19] "19"        "fizz"      "buzz"      "22"        "23"        "24"       
[25] "fizz"      "26"        "27"        "buzz"      "29"        "fizz"     
[31] "31"        "32"        "33"        "34"        "fizz buzz" "36"       
[37] "37"        "38"        "39"        "fizz"      "41"        "buzz"     
[43] "43"        "44"        "fizz"      "46"        "47"        "48"       
[49] "buzz"      "fizz"      "51"        "52"        "53"        "54"       
[55] "fizz"      "buzz"      "57"        "58"        "59"        "fizz"     
[61] "61"        "62"        "buzz"      "64"        "fizz"      "66"       
[67] "67"        "68"        "69"        "fizz buzz"

2. 与 if 语句一样,条件会按顺序进行检测,所以您应该将条件按照最严格到最宽松排列,否则会出现以下情况

x <- 1:70
case_when(x %%  5 == 0 ~ "fizz",x %%  7 == 0 ~ "buzz",x %% 35 == 0 ~ "fizz buzz",.default = as.character(x)
)
 [1] "1"    "2"    "3"    "4"    "fizz" "6"    "buzz" "8"    "9"   
[10] "fizz" "11"   "12"   "13"   "buzz" "fizz" "16"   "17"   "18"  
[19] "19"   "fizz" "buzz" "22"   "23"   "24"   "fizz" "26"   "27"  
[28] "buzz" "29"   "fizz" "31"   "32"   "33"   "34"   "fizz" "36"  
[37] "37"   "38"   "39"   "fizz" "41"   "buzz" "43"   "44"   "fizz"
[46] "46"   "47"   "48"   "buzz" "fizz" "51"   "52"   "53"   "54"  
[55] "fizz" "buzz" "57"   "58"   "59"   "fizz" "61"   "62"   "buzz"
[64] "64"   "fizz" "66"   "67"   "68"   "69"   "fizz"

3. 如果元素不符合任何条件,那么就会触发参数【.default】,默认为NA

x <- 1:70
case_when(x %% 35 == 0 ~ "fizz buzz",x %% 5 == 0 ~ "fizz",x %% 7 == 0 ~ "buzz",
)
 [1] NA          NA          NA          NA          "fizz"     [6] NA          "buzz"      NA          NA          "fizz"     
[11] NA          NA          NA          "buzz"      "fizz"     
[16] NA          NA          NA          NA          "fizz"     
[21] "buzz"      NA          NA          NA          "fizz"     
[26] NA          NA          "buzz"      NA          "fizz"     
[31] NA          NA          NA          NA          "fizz buzz"
[36] NA          NA          NA          NA          "fizz"     
[41] NA          "buzz"      NA          NA          "fizz"     
[46] NA          NA          NA          "buzz"      "fizz"     
[51] NA          NA          NA          NA          "fizz"     
[56] "buzz"      NA          NA          NA          "fizz"     
[61] NA          NA          "buzz"      NA          "fizz"     
[66] NA          NA          NA          NA          "fizz buzz"

4. 请注意,LHS 上的 NA 值将被视为 FALSE,并触发参数【.default】。如果要使用不同的值,必须明确处理它们。处理缺失值的具体方法取决于您使用的 LHS 条件集

x <- 1:70
x[2:4] <- NA_real_
case_when(x %% 35 == 0 ~ "fizz buzz",x %% 5 == 0 ~ "fizz",x %% 7 == 0 ~ "buzz",is.na(x) ~ "nope",.default = as.character(x)
)
 [1] "1"         "nope"      "nope"      "nope"      "fizz"     [6] "6"         "buzz"      "8"         "9"         "fizz"     
[11] "11"        "12"        "13"        "buzz"      "fizz"     
[16] "16"        "17"        "18"        "19"        "fizz"     
[21] "buzz"      "22"        "23"        "24"        "fizz"     
[26] "26"        "27"        "buzz"      "29"        "fizz"     
[31] "31"        "32"        "33"        "34"        "fizz buzz"
[36] "36"        "37"        "38"        "39"        "fizz"     
[41] "41"        "buzz"      "43"        "44"        "fizz"     
[46] "46"        "47"        "48"        "buzz"      "fizz"     
[51] "51"        "52"        "53"        "54"        "fizz"     
[56] "buzz"      "57"        "58"        "59"        "fizz"     
[61] "61"        "62"        "buzz"      "64"        "fizz"     
[66] "66"        "67"        "68"        "69"        "fizz buzz"

5. case_when() 对所有 RHS 表达式进行求值,然后通过提取所选(通过 LHS 表达式)部分来构建结果

y <- seq(-2, 2, by = .5)
case_when(y >= 0 ~ sqrt(y),.default = y
)
[1] -2.0000000 -1.5000000 -1.0000000 -0.5000000  0.0000000  0.7071068
[7]  1.0000000  1.2247449  1.4142136
Warning message:
In sqrt(y) : 产生了NaNs

6. 当你想创建一个依赖于现有变量复杂组合的新变量时,case_when() mutate() 中特别有用

starwars
# A tibble: 87 × 14name       height  mass hair_color skin_color eye_color birth_year<chr>       <int> <dbl> <chr>      <chr>      <chr>          <dbl>1 Luke Skyw…    172    77 blond      fair       blue            19  2 C-3PO         167    75 NA         gold       yellow         112  3 R2-D2          96    32 NA         white, bl… red             33  4 Darth Vad…    202   136 none       white      yellow          41.95 Leia Orga…    150    49 brown      light      brown           19  6 Owen Lars     178   120 brown, gr… light      blue            52  7 Beru Whit…    165    75 brown      light      blue            47  8 R5-D4          97    32 NA         white, red red             NA  9 Biggs Dar…    183    84 black      light      brown           24  
10 Obi-Wan K…    182    77 auburn, w… fair       blue-gray       57  
# ℹ 77 more rows
# ℹ 7 more variables: sex <chr>, gender <chr>, homeworld <chr>,
#   species <chr>, films <list>, vehicles <list>, starships <list>
# ℹ Use `print(n = ...)` to see more rows
starwars %>%select(name:mass, gender, species) %>%mutate(type = case_when(height > 200 | mass > 200 ~ "large",species == "Droid" ~ "robot",.default = "other"))
# A tibble: 87 × 6name               height  mass gender    species type <chr>               <int> <dbl> <chr>     <chr>   <chr>1 Luke Skywalker        172    77 masculine Human   other2 C-3PO                 167    75 masculine Droid   robot3 R2-D2                  96    32 masculine Droid   robot4 Darth Vader           202   136 masculine Human   large5 Leia Organa           150    49 feminine  Human   other6 Owen Lars             178   120 masculine Human   other7 Beru Whitesun Lars    165    75 feminine  Human   other8 R5-D4                  97    32 masculine Droid   robot9 Biggs Darklighter     183    84 masculine Human   other
10 Obi-Wan Kenobi        182    77 masculine Human   other
# ℹ 77 more rows
# ℹ Use `print(n = ...)` to see more rows

7. case_when() 不是一个整洁的条件函数。如果想重复使用相同的模式,请在自定义函数中调用 case_when()

case_character_type <- function(height, mass, species) {case_when(height > 200 | mass > 200 ~ "large",species == "Droid" ~ "robot",.default = "other")
}case_character_type(150, 250, "Droid")
case_character_type(150, 150, "Droid")
[1] "large"
[1] "robot"

8. 上述函数也可在 mutate() 中使用

starwars %>%mutate(type = case_character_type(height, mass, species)) %>%pull(type)
 [1] "other" "robot" "robot" "large" "other" "other" "other" "robot"[9] "other" "other" "other" "other" "large" "other" "other" "large"
[17] "other" "other" "other" "other" "other" "robot" "other" "other"
[25] "other" "other" "other" "other" "other" "other" "other" "other"
[33] "other" "other" "other" "large" "large" "other" "other" "other"
[41] "other" "other" "other" "other" "other" "other" "other" "other"
[49] "other" "other" "other" "other" "other" "other" "other" "large"
[57] "other" "other" "other" "other" "other" "other" "other" "other"
[65] "other" "other" "other" "other" "other" "other" "large" "large"
[73] "other" "robot" "other" "other" "other" "large" "large" "other"
[81] "other" "large" "other" "other" "other" "robot" "other"

9. case_when() 忽略 NULL 输入。当你想只在特定条件下使用模式时,这很有用。在这里,我们将利用 if 在没有 else 子句时返回 NULL 这一事实。

case_character_type <- function(height, mass, species, robots = TRUE) {case_when(height > 200 | mass > 200 ~ "large",if (robots) species == "Droid" ~ "robot",.default = "other")
}starwars %>%mutate(type = case_character_type(height, mass, species, robots = FALSE)) %>%pull(type)
 [1] "other" "other" "other" "large" "other" "other" "other" "other"[9] "other" "other" "other" "other" "large" "other" "other" "large"
[17] "other" "other" "other" "other" "other" "other" "other" "other"
[25] "other" "other" "other" "other" "other" "other" "other" "other"
[33] "other" "other" "other" "large" "large" "other" "other" "other"
[41] "other" "other" "other" "other" "other" "other" "other" "other"
[49] "other" "other" "other" "other" "other" "other" "other" "large"
[57] "other" "other" "other" "other" "other" "other" "other" "other"
[65] "other" "other" "other" "other" "other" "other" "large" "large"
[73] "other" "other" "other" "other" "other" "large" "large" "other"
[81] "other" "large" "other" "other" "other" "other" "other"

每种情况都按顺序进行检测,每个元素的第一个匹配值决定了其在输出向量中的相应值。如果没有匹配的情况,则使用 参数【.default】 作为最后的 "else "声明。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/494667.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

❤ 就这?TypeScript其实并不难!(建议收藏)❤

&#x1f388; 作者&#xff1a;不吃西红柿 &#x1f388; 简介&#xff1a;CSDN博客专家&#x1f3c6;、蓝桥签约作者、Python领域优质创作者、信息技术智库公众号创建者✌。技术交流、面试刷题尽管关注咨询我。 热门专栏推荐&#xff1a; &#x1f947; 知识集锦专栏&…

EntityModelStudio系列教程2--静态建模之实体模型设计

在EMStudio中静态建模的概念和内容是来自于UML标准的&#xff0c;所以EMStudio提供的静态建模的设计能力是完全可以满足开发者的设计要求的。但是与UML标准比较&#xff0c;EMStudio中的静态建模还存在两个不同的特色&#xff1a; 1. 类与实体的概念是一致的 也就是说&#xff…

Python 编码规范(Google) (一)

Python 风格规范(Google) 本项目并非 Google 官方项目, 而是由国内程序员凭热情创建和维护。 如果你关注的是 Google 官方英文版, 请移步 Google Style Guide 以下代码中 Yes 表示推荐&#xff0c;No 表示不推荐。 分号 不要在行尾加分号, 也不要用分号将两条命令放在同一行…

前沿科技山雨欲来,四大领域存创新机会

来源&#xff1a;北极光创投摘要&#xff1a;最近&#xff0c;北极光创投董事总经理杨磊&#xff0c;发表了《前沿科技山雨欲来》的主题演讲&#xff0c;他认为目前全球正处于前沿科技爆发前夜&#xff0c;他看好计算构架变革、移动终端、机器人、生物科技与IT融合四大领域的创…

❤JavaScript系列6部曲:语法篇(万字长文)❤

&#x1f388; 作者&#xff1a;不吃西红柿 &#x1f388; 简介&#xff1a;CSDN博客专家&#x1f3c6;、蓝桥签约作者、Python领域优质创作者、信息技术智库公众号创建者✌。技术交流、面试刷题尽管关注咨询我。 热门专栏推荐&#xff1a; &#x1f947; 知识集锦专栏&…

工业机器人发展现状:硬件制造大同小异,视觉感知绘新蓝图

来源 &#xff1a;亿欧摘要&#xff1a;8月15日-8月19日&#xff0c;在北京亦庄国际会展中心举办了为期五天的2018世界机器人大会。小编认为&#xff0c;国内工业机器人的总体水平在未来长期时间将处于稳定上升区&#xff0c;而两极分化趋势愈显。8月15日-8月19日&#xff0c;在…

❤️JavaScript系列6部曲:流程控制(万字长文)❤️

&#x1f388; 作者&#xff1a;不吃西红柿 &#x1f388; 简介&#xff1a;CSDN博客专家&#x1f3c6;、蓝桥签约作者、Python领域优质创作者、「信息技术智库」公号作者✌。技术交流、面试刷题尽管关注咨询我。 热门专栏推荐&#xff1a; &#x1f947; 知识集锦专栏&…

[C# 网络编程系列]专题七:UDP编程补充——UDP广播程序的实现

本专题主要介绍下如何实现UDP广播的程序&#xff0c;下面就直接介绍实现过程和代码以及运行的结果。 一、程序实现 UDP广播程序的实现代码&#xff1a; using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.W…

我们离得开美国的软件和硬件吗?

来源&#xff1a;网易科技摘要&#xff1a;据报道&#xff0c;你当然可以淘汰很多美国产品&#xff0c;但你可能也会因此放弃许多令人惊叹的功能。据报道&#xff0c;你当然可以淘汰很多美国产品&#xff0c;但你可能也会因此放弃许多令人惊叹的功能。例如&#xff0c;超过10亿…

PostgreSQL连接池pgbouncer的使用

今天在虚拟机上整理了下pgbouncer的安装使用过程&#xff0c;记录如下。 说明&#xff1a;pgbouncer是一款轻量级针对postgresql的数据库连接工具&#xff0c;可以对客户端的连接做限制&#xff0c;防止恶意连接&#xff0c;另外也可以减少数据库的实际连接数&#xff0c;从而减…

❤️❤️❤️【资料免费领取】简历模板、职场PPT模板、硬核学习资料+PDF资料(Java、Python、大数据、机器学习)❤️❤️❤️

&#x1f345;【领取方法】 长按识别二维码&#xff0c;回复【资料】领取 目录 1、100套小编购买的简历模板&#xff08;部分截图&#xff09; 2、1000套精品PPT模板&#xff08;部分截图&#xff09; 3、大数据-学习资料&#xff08;1.3G 硬核PDF&#xff0c;官方指南&…

超20亿!2018年国家自然科学基金(重点项目)出炉!

来源&#xff1a;青塔摘要&#xff1a;8月16日&#xff0c;2018年国家自然科学基金评审结果正式揭晓。8月16日&#xff0c;2018年国家自然科学基金评审结果正式揭晓。继昨天发布了2018年国家优青项目各单位的立项情况后&#xff0c;青塔今天又整理重点项目的立项情况和完整名单…

❤️ 珊姐带你学JavaScript:数组和函数 (万文建藏)❤️

&#x1f345; 作者&#xff1a;阿珊 &#x1f345; 简历模板、职场PPT模板、技术交流尽管关注私聊我。 &#x1f345; 期许&#xff1a;欢迎点赞 &#x1f44d; 收藏 ⭐留言 &#x1f4dd; 如有错误敬请指正&#xff01; 热门专栏推荐&#xff1a; &#x1f947; 大数据集锦…

查看本机打开的端口

一、怎样查看本机打开的端口&#xff1f;1&#xff0e; Windows本身自带的netstat命令 Netstat 显示协议统计和当前的 TCP/IP 网络连接。该命令只有在安装了 TCP/IP 协议后才可以使用。 netstat [-a] [-e] [-n] [-s] [-p protocol] [-r] [interval] 参数 -a 显示所有连接和侦…

产业|中国电子学会发布《机器人十大新兴应用领域(2018-2019年)》

来源&#xff1a; 中国电子学会8月19日&#xff0c;2018世界机器人大会胜利闭幕&#xff0c;闭幕式上中国电子学会发布了《发布机器人十大新兴应用领域&#xff08;2018-2019年&#xff09;》。当前&#xff0c;全球正在经历科技、产业、资本高度耦合、深度迭加的新一轮变革&am…

在linux下添加路由

linux下添加路由的方法&#xff1a;   一&#xff1a;使用 route 命令添加   使用route 命令添加的路由&#xff0c;机器重启或者网卡重启后路由就失效了&#xff0c;方法&#xff1a;   //添加到主机的路由   # route add –host 192.168.168.110 dev eth0   # rout…

2018-2019年新一代AI领域十大最具成长性技术展望

来源&#xff1a;网络大数据摘要&#xff1a;在2018世界机器人大会17日的主论坛上&#xff0c;中国电子学会发布《新一代人工智能领域十大最具成长性技术展望(2018-2019年)》。当前&#xff0c;全球正在经历科技和产业高度耦合、深度迭加的新一轮变革&#xff0c;大数据的形成、…

wzplayer for android V1.0

V1.0上图,哈哈 转载于:https://www.cnblogs.com/weinyzhou/archive/2012/10/12/2750055.html

全球公有云巨头:亚马逊 AWS

来源&#xff1a;乐晴智库精选摘要&#xff1a;亚马逊AWS目前拥有超过1500种产品和2100余种第三方模块&#xff0c;为全球190个国家的企业提供支持。AWS作为亚马逊旗下的云计算服务平台&#xff0c;面向全世界范围的用户提供包括弹性计算、存储、数据库、应用程序在内的一整套云…

地灾应急暨地灾危险性评估培训班学习笔记

前一阵子单位安排到新疆参加了一个培训&#xff0c;关于地灾应急和危险性评估方面的&#xff0c;培训时间不长&#xff0c;不过信息量挺大&#xff0c;学习的时候做了一些读书笔记如下&#xff1a;首先讲到关于加强地质灾害防治工作的内容&#xff0c;其中有提到关于地质灾害信…