gpt4 book ai didi

r - 我应该如何使用嵌套的 ifelse 语句?

转载 作者:行者123 更新时间:2023-12-02 05:28:02 25 4
gpt4 key购买 nike

我用以下数据创建了一个数据框

name <- c("A","B","C","D","E","F","G","H","I","J")
age <- c(22,43,12,17,29,5,51,56,9,44)
sex <- c("M","F","M","M","M","F","F","M","F","F")
rock <- data.frame(name,age,sex,stringsAsFactors = TRUE)
rock

现在我想知道:

如果姓名为 E 到 J,性别不等于 F,则状态为“1F”,如果姓名为 A 到 D,且年龄大于 15 岁,则状态为“年轻”。其他都是“其他”

为此,我正在应用以下代码:

rock$status <- ifelse(rock$name==c("E","F","G","H","I","J")& 
rock$sex!="F","1F",
ifelse(rock$name==c("E","F","G","H","I","J")&rock$sex=="F","Fenamle",
ifelse(rock$name==c("A","B","C","D") & rock$age>15,"Young","Others")))
rock

但我得到的输出如下:

  name  age    sex    status
1 A 22 M Young
2 B 43 F Young
3 C 12 M Others
4 D 17 M Young
5 E 29 M Others
6 F 5 F Others
7 G 51 F Others
8 H 56 M Others
9 I 9 F Others
10 J 44 F Others

但是,它必须在 E 和 H 上显示为“1F”,但显示为“其他”

我的代码做错了什么?

请大家指正并给我一些宝贵的建议。

最佳答案

我们需要使用%in%代替==:

rock$status <- ifelse(rock$name %in% c("E", "F", "G", "H", "I", "J") & 
rock$sex != "F", "1F",
ifelse(rock$name %in% c("E", "F", "G", "H", "I", "J") &
rock$sex == "F", "Female",
ifelse(rock$name %in% c("A", "B", "C", "D") &
rock$age > 15, "Young", "Others")))
rock

# name age sex status
# 1 A 22 M Young
# 2 B 43 F Young
# 3 C 12 M Others
# 4 D 17 M Young
# 5 E 29 M 1F
# 6 F 5 F Female
# 7 G 51 F Female
# 8 H 56 M 1F
# 9 I 9 F Female
# 10 J 44 F Female

关于r - 我应该如何使用嵌套的 ifelse 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46561085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com