Home > Enterprise >  How to mutate in using a for loop to assign values iteratively in R using dplyr?
How to mutate in using a for loop to assign values iteratively in R using dplyr?

Time:10-08

Where I am adding the runif(1,0,8) I want that to be a different number for each row, but at the moment it is the same random number. How do I loop through the rows iteratively to assign a different value to add each time? Thanks!

  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))```


CodePudding user response:

You can use rowwise so get a different random number at every row:

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

Created on 2021-10-07 by the enter image description here

As you can see the Noise Amount is the same. This is because runif function first argument is 1 in the function so it is only producing one random number. Take a look at ?runif to see how the runif function works.

Here is a way to add noise to all the rows uniquely

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


enter image description here

The difference here being length(Numbers) as the first argument in the runif function. This produces a vector of random numbers the same size as the Numbers variable I defined which are then added to each row in a vector fashion.

  • Related