You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中基于逻辑变量筛选Homicide.rate数值的技术求助

Fixing HRate and LRate Generation in R

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 (lowercase i at the end)
  • But then you tried to use Homicide_Index (uppercase I at 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:27:48