如何使用 dplyr 生成列相关随机变量
How to generate column dependent random variable with dplyr
我想生成一列正态随机变量,均值在 dep 变量中定义。但是,我得到了非随机结果。
我知道还有其他方法可以做到这一点,比如应用函数 (sapply(1:5, rnorm, n=1)
),但我只是想知道如何使用 dplyr 来做到这一点以及为什么我会出错。
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
尝试添加 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
我认为 rowwise
很慢。相反,您应该将第一个参数更正为 rnorm
:
data.frame(dep=1:5) %>% mutate(normal_mean = rnorm(n(), mean=dep))
我想生成一列正态随机变量,均值在 dep 变量中定义。但是,我得到了非随机结果。
我知道还有其他方法可以做到这一点,比如应用函数 (sapply(1:5, rnorm, n=1)
),但我只是想知道如何使用 dplyr 来做到这一点以及为什么我会出错。
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
尝试添加 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
我认为 rowwise
很慢。相反,您应该将第一个参数更正为 rnorm
:
data.frame(dep=1:5) %>% mutate(normal_mean = rnorm(n(), mean=dep))