如何在R语言中使用if-else语句?并编写指定逻辑的dayplan函数
First, let's recap how if-else works in R—it's our go-to control structure for conditional execution:
- Use
if(condition)to run code when the condition evaluates to TRUE. - Add
else if(another_condition)for sequential additional checks. - Use
elseas a catch-all for cases where none of the prior conditions are met.
Now, let's build your dayplan(temperature, work) function step by step.
Step 1: Input Validation
First, we need to enforce valid inputs to avoid unexpected behavior:
temperaturemust be a numeric value between -20 and 40 (inclusive).workmust be exactly either "Yes" or "No" (case-sensitive, per your requirements).
We'll use stop() to throw clear, helpful error messages if inputs are invalid.
Step 2: Fixing & Implementing Conditional Logic
Looking at your requirements, there's a small overlap in the conditions: the first rule (temperature >=20 and work=="Yes") includes the third rule (temperature>20 and work=="Yes"), which means the third condition would never actually run. I assume this is a typo, so I've adjusted it to temperature <20 and work=="Yes" to make the logic complete (outputting "Shopping" for that case). If my assumption is wrong, you can tweak the condition easily!
Putting it all together, here's the full function:
dayplan <- function(temperature, work) { # Validate temperature input if (!is.numeric(temperature) || temperature < -20 || temperature > 40) { stop("temperature must be a numeric value between -20 and 40") } # Validate work input if (!work %in% c("Yes", "No")) { stop("work must be either 'Yes' or 'No'") } # Execute the day plan logic if (temperature >= 20 && work == "Yes") { "Eat ice cream" } else if (temperature >= 20 && work == "No") { "Sea" } else if (temperature < 20 && work == "Yes") { # Adjusted condition here "Shopping" } else { # Covers temperature <20 and work=="No" "Bed" } }
Step 3: Test the Function
Let's test some valid and invalid cases to confirm it works:
- Valid inputs:
dayplan(25, "Yes") # Returns "Eat ice cream" dayplan(22, "No") # Returns "Sea" dayplan(15, "Yes") # Returns "Shopping" dayplan(5, "No") # Returns "Bed" - Invalid inputs:
dayplan(45, "Yes") # Throws error: temperature out of range dayplan(20, "yes") # Throws error: work must be "Yes" or "No" (case-sensitive)
Quick Notes
- If you intended the third condition to be something else (like
temperature > 30instead of>20), just modify thatelse ifline— the structure is flexible. - In R, we don't always need
return(); the last evaluated expression in the function is automatically returned, which is what I used here.
内容的提问来源于stack exchange,提问作者Lira

