R中阈值处的整数

Round numbers at a threshold value in R

我正在尝试进行逻辑回归,我已经达到了我对每个观察都有概率的地步。现在我想在给定阈值

的情况下将概率分类为 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。但它只是不太优雅。

我想知道是否有任何函数可以以更简单的方式执行此操作?

听起来 ifelse 可以满足您的要求?

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