【问题标题】:Exclude 0's while random number generation using base sample使用基本样本生成随机数时排除 0
【发布时间】:2020-08-12 15:05:58
【问题描述】:

我有一个如下所示的数据框

  id    shift_back shift_forward
  <chr>      <dbl>         <dbl>
1 11          -140             0
2 12           -63           149
3 13           -37           327
4 14             0           193
5 16           -30            30
6 17           -30            30
7 18           -30            30
8 19           -30            30

我想以shift_backshift_forward 这些列作为范围间隔生成一个随机数。

但是,我不希望随机数是 0

以下代码可以正常工作,但也包含 0

mutate(shift = base::sample(seq(shift_back, shift_forward, by = 1), 1))

但是,这会产生如下所示的输出,其中0 也可以作为移位值

如何生成范围内但不包括 0(从区间)的随机数。基本上我不希望移位值为 0(零)。

【问题讨论】:

    标签: r dataframe dplyr tidyr purrr


    【解决方案1】:

    您可以在采样前排除零。

    library(dplyr)
    
    df %>%
      rowwise() %>% 
      mutate(shift = seq(shift_back, shift_forward) %>% .[. != 0] %>% sample(1))
    

    【讨论】:

    • 您好,请问.[.!=0]中的外圆点和内圆点是什么意思?
    • @TheGreat 实际上,seq(a, b) %&gt;% .[. != 0] 等价于 seq(a, b)[seq(a, b) != 0]。因为seq(a, b)出现了两次,所以我把它移到一个管道的前面,管道后面的"."代表它。
    【解决方案2】:
    library(tidyverse)
    
    df <- tibble(
      id = 11:14,
      shift_back = c(-140, -63, -37, 0),
      shift_forward = c(0,149, 327, 193)
    )
    
    df %>%
      rowwise() %>%
      mutate(shift = list(seq(shift_back, shift_forward, by = 1)),
             shift = list(shift[shift != 0]),
             shift = sample(shift, 1))
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    相关资源
    最近更新 更多