R语言中基于逻辑变量筛选Homicide.rate数值的技术求助
Hey there! Let's troubleshoot why your code isn't working and get those variables created correctly.
The Immediate Issue: Case Sensitivity
First off, R is case-sensitive, and you've got a mismatch in your variable names:
- You defined your logical index as
Homicide_index(lowercaseiat the end) - But then you tried to use
Homicide_Index(uppercaseIat the end)
That's why your code is failing—R can't find the variable you're referencing. Let's fix that first:
# First, define your logical index with a consistent name Homicide_index <- ifelse(gunData$Homicide.rate > 4.3, TRUE, FALSE) # Now use the exact same variable name to subset HRate <- gunData$Homicide.rate[which(Homicide_index)] LRate <- gunData$Homicide.rate[which(!Homicide_index)]
A More Streamlined Approach
You don't even need to create a separate logical index variable if you don't want to—you can subset directly with the condition, which is often more readable:
# Get all Homicide.rate values greater than 4.3 HRate <- gunData$Homicide.rate[gunData$Homicide.rate > 4.3] # Get all remaining Homicide.rate values LRate <- gunData$Homicide.rate[gunData$Homicide.rate <= 4.3]
Handling NA Values
If your Homicide.rate column has missing values (NA), the above code will include those NAs in LRate (since NA <= 4.3 returns NA, which gets kept in the subset). To exclude NAs entirely, add a check for non-missing values:
HRate <- gunData$Homicide.rate[gunData$Homicide.rate > 4.3 & !is.na(gunData$Homicide.rate)] LRate <- gunData$Homicide.rate[gunData$Homicide.rate <= 4.3 & !is.na(gunData$Homicide.rate)]
Quick Note on which()
Using which() converts the logical vector to numeric indices, but in R, you can use the logical vector directly for subsetting (like in the streamlined example) — both methods work, but the direct subset is often cleaner.
内容的提问来源于stack exchange,提问作者Kajamaz

