R 中等效的 Case 语句 [英] Case Statement Equivalent in R
本文介绍了R 中等效的 Case 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在数据框中有一个变量,其中一个字段通常有 7-8 个值.我想在数据框中的新变量中将它们折叠 3 或 4 个新类别.最好的方法是什么?
I have a variable in a dataframe where one of the fields typically has 7-8 values. I want to collpase them 3 or 4 new categories within a new variable within the dataframe. What is the best approach?
如果我使用的是类似 SQL 的工具,但不确定如何在 R 中进行攻击,我会使用 CASE 语句.
I would use a CASE statement if I were in a SQL-like tool but not sure how to attack this in R.
您能提供的任何帮助将不胜感激!
Any help you can provide will be much appreciated!
推荐答案
case_when()
于 2016 年 5 月加入 dplyr,以类似于 memisc 的方式解决了这个问题::cases()
.
case_when()
, which was added to dplyr in May 2016, solves this problem in a manner similar to memisc::cases()
.
例如:
library(dplyr)
mtcars %>%
mutate(category = case_when(
.$cyl == 4 & .$disp < median(.$disp) ~ "4 cylinders, small displacement",
.$cyl == 8 & .$disp > median(.$disp) ~ "8 cylinders, large displacement",
TRUE ~ "other"
)
)
从 dplyr 0.7.0 开始,
As of dplyr 0.7.0,
mtcars %>%
mutate(category = case_when(
cyl == 4 & disp < median(disp) ~ "4 cylinders, small displacement",
cyl == 8 & disp > median(disp) ~ "8 cylinders, large displacement",
TRUE ~ "other"
)
)
这篇关于R 中等效的 Case 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文