R语言:为函数添加if.else语句返回null及阈值定位问题
Hey there! Let's work through your two R questions step by step:
I’ll assume you have a function where you want to return a specific result when a condition is met, and the string "null" otherwise. Let’s use a simple example to demonstrate:
Suppose your original function looks like this (it multiplies a number by 2 only if it’s greater than 5):
my_function <- function(x) { if (x > 5) { x * 2 } }
To modify it so it returns "null" when the condition isn’t satisfied, just add an else clause:
my_function <- function(x) { if (x > 5) { x * 2 } else { "null" # Returns the string "null" as requested } }
Quick note: If you actually wanted to return R’s built-in NULL value (not the string), just remove the quotes around null. But based on your request, the string version is what you need.
First, let’s recreate your OD data frame to work with:
# Build the data frame from your provided data od_data <- data.frame( time = c(446, 446.5, 447, 447.5, 448, 448.5, 449, 449.5, 450, 450.5, 451, 451.5, 452, 452.5, 453, 453.5), OD = c(0.0368, 0.0353, 0.0334, 0.032, 0.0305, 0.0294, 0.0281, 0.0264, 0.0255, 0.0246, 0.0238, 0.0225, 0.0211, 0.0199, 0.0189, 0.0175) )
Next, define your upper and lower thresholds. I’ll use example values here—replace them with your actual thresholds:
# Set your threshold values upper_thresh <- 0.035 # Example upper limit lower_thresh <- 0.022 # Example lower limit
To find the first time the OD value goes outside these thresholds (either above upper or below lower), use which() to get the index of the first matching row, then pull the corresponding time and OD value:
# Find the first index where OD crosses the thresholds first_cross_index <- which(od_data$OD > upper_thresh | od_data$OD < lower_thresh)[1] # Handle cases where no values cross the thresholds if (is.na(first_cross_index)) { cat("None of the OD values crossed your specified thresholds.\n") } else { first_cross_time <- od_data$time[first_cross_index] first_cross_OD <- od_data$OD[first_cross_index] cat("First time OD crossed thresholds:", first_cross_time, "\nCorresponding OD value:", first_cross_OD, "\n") }
If you instead wanted to find the first OD value that falls inside the threshold range (between lower and upper), just adjust the condition inside which():
first_in_range_index <- which(od_data$OD >= lower_thresh & od_data$OD <= upper_thresh)[1]
This will give you the first row where OD is within your desired bounds.
内容的提问来源于stack exchange,提问作者amir.fathi

