如何使用R中的嵌套ifelse()对数据进行编码
我在R中嵌套的ifelse()语句中遇到了一个问题。我有一个数据帧,它有一个列年龄。我必须按照以下条件对数据进行编码-如何使用R中的嵌套ifelse()对数据进行编码,r,R,我在R中嵌套的ifelse()语句中遇到了一个问题。我有一个数据帧,它有一个列年龄。我必须按照以下条件对数据进行编码- 如果是18岁和60岁,那么年龄=老年人 我使用以下代码来解决这个问题 ifelse((Titanic$Age <= 18),Titanic$Age <-'child',ifelse((Titanic$Age>18 & Titanic$Age<=60),Titanic$Age <- 'adult',Titanic$Age <- 'sen
ifelse((Titanic$Age <= 18),Titanic$Age <-'child',ifelse((Titanic$Age>18 & Titanic$Age<=60),Titanic$Age <- 'adult',Titanic$Age <- 'senior'))
ifelse((泰坦尼克号$Age您可以在dplyr
中使用case\u。它允许向量化多个if\u else
语句:
library(dplyr)
set.seed(111)
df <- data.frame(Age = runif(100, 0, 90))
df <- df %>% mutate(Age = case_when(Age <= 18 ~ "child 2",
Age > 18 & Age <= 60 ~ "adult 3",
TRUE ~ "senior"))
由于具有数值,因此可以使用“剪切”,然后重命名标高。
这只使用基函数
# some dummy data
dummy <- data.frame(age = runif(100, 0,100))
# actual code:
# cut the data based on the thresholds. Look into the documentation to see whether the sets borders are included to the left or the right.
dummy$agebracket <- cut(dummy$age, breaks = c(0,18,60,9999))
# now we just rename them to our liking
levels(dummy$agebracket) <- c("child 1", "child 2", "senior")
#一些虚拟数据
dummy解释代码不工作的原因:当您这样做时
ifelse(
Titanic$Age <= 18,
Titanic$Age <-'child',
ifelse(...)
)
但是在几个嵌套的ifelse
语句之后,这就变得很难阅读了,所以我推荐case\u当dplyr
中的如@slava kohut在他的回答中所示。最好保留原始数据,并在年龄旁边添加一个分类栏
一个没有包装的直接答案如下:
Titanic$categeory <- with(Titanic, ifelse(Age<18,yes = "child2",no = ifelse(Age<=60,yes = "Adult",no = "Senior")))
Titanic$categoryifelse
返回要分配的值;不要使用
Titanic$agebracket <-
ifelse((Titanic$Age <= 18), 'child',
ifelse((Titanic$Age>18 & Titanic$Age<=60),'adult', 'senior'))
ifelse(
Titanic$Age <= 18,
Titanic$Age <-'child',
ifelse(...)
)
ifelse(
Titanic$Age <= 18,
'child',
ifelse(...)
)
Titanic$categeory <- with(Titanic, ifelse(Age<18,yes = "child2",no = ifelse(Age<=60,yes = "Adult",no = "Senior")))