【问题标题】:R: Tie Simulations in dplyr mutateR:dplyr mutate 中的平局模拟
【发布时间】:2019-04-09 15:26:24
【问题描述】:

我想在 tibble 中生成二元分布。这是我正在尝试创建的内容:

library(copula); library(tidyverse)
n <- 10e3; alpha <- 2.6
tib1 <- tibble(locid = seq(n))
tib2 <- rCopula(n, gumbelCopula(alpha)) %>% as_tibble
plot(tib2$V1, tib2$V2)

cor(tib2$V1, tib2$V2) 大致是0.8

但是,当我将其作为函数插入 tibble 时,它​​似乎没有按预期工作,即 K1 和 K2 不相关。

testfn <- function(n) rCopula(n, gumbelCopula(alpha)) %>% as_tibble

tib3 <- tib1 %>% 
mutate(K1 = testfn(n)$V1,
       K2 = testfn(n)$V2)

即cor(tib3$K1, tib3$K2) 是 zero

我之所以想在 dplyr 中执行此操作,而不是执行诸如 cbind 之类的操作,是因为我想在 mutate 函数中操作 K1 和 K2。

谢谢。

【问题讨论】:

  • 你好@akrun 这是什么意思?
  • 我的意思是把它包装在一个列表中。 BTW,请指定使用的包rCopula
  • 对不起@akrun,我已经添加了那个包。不确定我是否遵循您的列表建议...

标签: r dplyr


【解决方案1】:

问题出在您的 mutate 语句中;您将调用函数 testfn(n) 两次(从而模拟两组新数据)并使用第一次调用的输出中的 V1 分配 K1,使用第二次调用的 V2 分配 K2。

您想使用已在 tib1 中定义的数据。

由于 tib1 已经通过管道传递给 mutate() (tib1 %&gt;% mutate(...)),所以在分配 K1 和 K2 时可以直接引用 V1 和 V2:

set.seed( 1337 ) # set the RNG
library(copula); # for rCopula()
library(tidyverse); # for dplyr::mutate() and pipe syntax (%>%)
n <- 10e3; alpha <- 2.6; # define simulation parameters

# wrap the rCopula call in a function that returns a tibble
testfn <- function(n, .alpha = alpha){ rCopula(n, gumbelCopula(.alpha)) %>% as_tibble }

tib1 <- testfn(n)


# assign K1 and K2 using V1 and V2 (piped in from tib1),
# assign K1old and K2old using output from two (independent) calls to testfn(n)
tib3  <- tib1 %>%
  mutate(K1 = V1,
         K2 = V2,
         K1old = testfn(n)$V1,
         K2old = testfn(n)$V2,)

测试相关性,

# correlations
tib3 %>% summarize(cor(K1old, K2old)) ## -0.0148
tib3 %>% summarize(cor(K1, K2)) ## 0.808

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 2016-02-28
    • 2016-11-15
    相关资源
    最近更新 更多