【问题标题】:How to mutate in using a for loop to assign values iteratively in R using dplyr?如何在使用 for 循环中使用 dplyr 在 R 中迭代地赋值?
【发布时间】:2021-11-27 14:33:38
【问题描述】:

我在哪里添加 runif(1,0,8) 我希望它是每一行的不同数字,但目前它是相同的随机数。如何迭代地遍历行以分配不同的值以每次添加?谢谢!

  mutate(enter_sim_time = arrive_hrs) %>% #add column for arrival time
  
  mutate(exc_flag = rbinom(demand, 1, runif(1,0.34,0.37)))  %>% #add a column to flag whether a work item is routed to exceptions or not 
  mutate(exc_enter_sim_time = ifelse(exc_flag == 1, enter_sim_time + runif(1,0,8), enter_sim_time))```


【问题讨论】:

    标签: r for-loop dplyr


    【解决方案1】:

    这是一个尝试向某些数据添加一些噪音的示例

    library(dplyr)
    
    df <- data.frame(Numbers = seq(1,10))
    
    df %>% 
      mutate(Numbers.Noise = Numbers + runif(1, 0, 1)) %>% 
      mutate(Noise.Amount =  Numbers.Noise - Numbers)
    
    

    如您所见,噪声量是相同的。这是因为runif 函数的第一个参数在函数中是 1,所以它只产生一个随机数。查看?runif 以了解runif 函数的工作原理。

    这是一种为所有行唯一地添加噪声的方法

    df %>% 
      mutate(Numbers.Noise = Numbers + runif(length(Numbers), 0, 1)) %>% 
      mutate(Noise.Amount =  Numbers.Noise - Numbers)
    
    
    

    这里的区别在于length(Numbers) 作为runif 函数中的第一个参数。这会生成一个与我定义的 Numbers 变量大小相同的随机数向量,然后以向量方式将其添加到每一行。

    【讨论】:

      【解决方案2】:

      您可以使用rowwise,以便在每一行获得不同的随机数:

      library(tidyverse)
      set.seed(1337)
      
      iris %>%
        as_tibble() %>%
        rowwise() %>%
        mutate(
          flag = rbinom(1, 1, 0.5),
          number = runif(1,0,8)
        ) %>%
        ungroup()
      #> # A tibble: 150 x 7
      #>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species  flag number
      #>           <dbl>       <dbl>        <dbl>       <dbl> <fct>   <int>  <dbl>
      #>  1          5.1         3.5          1.4         0.2 setosa      1   6.09
      #>  2          4.9         3            1.4         0.2 setosa      1   1.01
      #>  3          4.7         3.2          1.3         0.2 setosa      0   1.80
      #>  4          4.6         3.1          1.5         0.2 setosa      0   2.14
      #>  5          5           3.6          1.4         0.2 setosa      0   4.12
      #>  6          5.4         3.9          1.7         0.4 setosa      0   5.86
      #>  7          4.6         3.4          1.4         0.3 setosa      1   7.05
      #>  8          5           3.4          1.5         0.2 setosa      0   2.80
      #>  9          4.4         2.9          1.4         0.2 setosa      0   3.51
      #> 10          4.9         3.1          1.5         0.1 setosa      0   3.53
      #> # … with 140 more rows
      

      reprex package 创建于 2021-10-07 (v2.0.1)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-09
        • 2022-12-08
        • 1970-01-01
        • 2020-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多