我創建了一個數據幀數據如下我應該如何使用嵌套的ifelse語句?
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
但是,它必須是「1F 「在E和H上,但它顯示」其他「
我的代碼有什麼問題?
請糾正我,也給我一些關於此的寶貴建議。
相關崗位:https://stackoverflow.com/questions/42637099/difference-between-the-and-in-operators -in-r – zx8754