【问题标题】:How to generate column dependent random variable with dplyr如何使用 dplyr 生成列相关随机变量
【发布时间】:2015-05-20 14:23:11
【问题描述】:

我想生成一列正常随机变量,其均值在 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() 逐行解决问题

标签: r dplyr


【解决方案1】:

我认为rowwise 很慢。相反,您应该将第一个参数更正为rnorm

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

【讨论】:

  • nrow(.) 不适用于我,但如果需要,可以将其替换为 n()
  • @aosmith 谢谢,你是对的(尽管两者都对我有用)。我会改用那个,因为它更惯用。最近我收到很多错误,比如“不,不要直接使用n()”,所以我放弃了。
  • 这也适用于在dplyr::mutate 中使用其他类似功能,例如base::sample。例如。 base::sample(x, n(), replace = TRUE) 而不是 base::sample(x, 1)
【解决方案2】:

尝试添加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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-27
    • 2014-07-13
    • 2020-01-30
    • 2017-05-15
    • 1970-01-01
    • 2013-05-18
    • 2017-06-12
    • 1970-01-01
    相关资源
    最近更新 更多