【问题标题】:Round numbers at a threshold value in RR中阈值处的整数
【发布时间】:2017-05-15 05:31:35
【问题描述】:

我正在尝试进行逻辑回归,并且达到了每次观察都有概率的地步。现在我想在给定阈值的情况下将概率分类为 0 或 1

例如,如果我有两个数字 0.65 和 0.87,我的阈值为 0.7,我想将 0.65 舍入为 0,将 0.87 舍入为 1。

为了实现这一点,我尝试了以下代码,我认为对于这样一个简单的任务来说太多了,我想知道是否有专门执行此操作的函数。

library(tidyverse)

# create a table of probabilities and predictions (0 or 1)
df <- tibble(
  prob = runif(20),
  pred = round(prob) # threshold = 0.5
)

# threshold function for length = 1
threshold_1 <- function(p,t) {
  if (p > t) 1 else 0
}

# threshold function for length = p
threshold_p <- function(ps, t) {
  map2_dbl(ps, t, threshold_1)
}

# below works.
df %>% mutate(
  pred = threshold_p(df$prob, 0.7)
)

我也试过了

# threshold = 0.7
df %>%
  mutate(
  pred = round(prob - 0.2) # threshold = 0.7
)

上面的效果非常好,因为没有概率正好是 0 或 1(只要我们处理分布函数),所以即使我对数字 +/- 0.5(改变阈值),它们也会从不舍入到 -1 或 2。只是它不是很优雅。

我想知道是否有任何功能可以以更简单的方式做到这一点?

【问题讨论】:

  • 只是as.numeric(prob &gt; 0.7)findInterval(prob, 0.7)?

标签: r tidyverse


【解决方案1】:

听起来像ifelse 可以做你想做的事?

library(dplyr)
df %>% 
  mutate(pred = ifelse(prob < 0.7, 0, 1))

【讨论】:

  • df %>% mutate(pred = if(prob
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多