简体   繁体   中英

R: Tie Simulations in dplyr mutate

I would like to generate a bivariate distribution within a tibble. Here is what I'm attempting to create:

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)

一只忙碌的猫

Where cor(tib2$V1, tib2$V2) is roughly 0.8

However, when I insert this as a function into a tibble, it does not seem to work as expected ie K1 and K2 are uncorrelated.

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

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

ie cor(tib3$K1, tib3$K2) is zero

The reason why I'd like to do this in dplyr instead doing something like, cbind , for example is because I want to manipulate K1 and K2 within the mutate function.

Thank you.

The problem is within your mutate statement; you're calling the function testfn(n) twice (thereby simulating two new sets of data) and assigning K1 using V1 from the first call's output and K2 using V2 from the second call.

You want to use the data already defined in tib1.

Since tib1 is already piped in to mutate() ( tib1 %>% mutate(...) ), you can reference V1 and V2 directly when assigning K1 and K2:

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

Testing the correlations,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM