R中的等效案例声明 [英] Case Statement Equivalent in R
本文介绍了R中的等效案例声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个数据帧中有一个变量,其中一个字段通常具有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中的等效案例声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文