How to create a random column dependent variable with dplyr

I want to create a column of normal random variables with the mean defined in the dep variable. However, I got non-random results.

I know there are other ways to do this, how to apply the ( sapply(1:5, rnorm, n=1)

) functions , but I'm just curious to know how to do this using dplyr and why I got errors.

library(dplyr)
data_frame(dep = 1:5) %>% 
        mutate(normal_mean = rnorm(1, mean=dep))
Source: local data frame [5 x 2]

dep normal_mean
1   1    1.574045
2   2    1.574045
3   3    1.574045
4   4    1.574045
5   5    1.574045

      

+3


source to share


2 answers


I think rowwise

very slow. Instead, you should just fix the first argument rnorm

:



data.frame(dep=1:5) %>% mutate(normal_mean = rnorm(n(), mean=dep))

      

+4


source


Try adding rowwise()



library(dplyr)
data_frame(dep = 1:5) %>% 
  rowwise() %>%
  mutate(
    normal_mean = rnorm(1, mean=dep)
  )

  dep normal_mean
1   1   2.0999493
2   2   0.8764449
3   3   6.4460789
4   4   3.2802778
5   5   4.6731459

      

+1


source







All Articles