dplyr, dunn test, Error in dim(robj) <- c(dX, dY) : dims [product 0] do not match the length of object

838 Views Asked by At

I am trying to pass a dataset filtered by a variable value to the pairw.kw function from the "asbio" package in R.

example.df <- data.frame( 
                 species = sample(c("primate", "non-primate"), 50, replace = TRUE),
                 treated = sample(c("Yes", "No"), 50, replace = TRUE), 
                 gender = sample(c("male", "female"), 50, replace = TRUE), 
                 var1 = rnorm(50, 100, 5)
               )

library(dplyr)
library(asbio)

with(example.df, pairw.kw(var1, species, conf=0.95))

This code works. However,

example.df %>% 
   filter(treated=="No") %>% 
   {pairw.kw("var1", "species",conf = 0.95)}

gives me the error message

Error in dim(robj) <- c(dX, dY) : dims [product 0] do not match the length of object [1]

I cannot understand what is causing this, other than to assume that the two vectors being compared become different lengths after the filter is applied.

Is there a way to fix this other than subsetting the data explicitly to a new dataframe and using that instead? I know that will work, but wanted to know if a more elegant solution exists.

1

There are 1 best solutions below

4
On BEST ANSWER

First of all %>% pipe passes a data.frame to the pairw.kw function as a first argument. Secondly, pairw.kw function wants two vectors as an input. You can achive this with %$% pipe from magrittr package. It works similar to with function.

library(magrittr)

example.df %>% 
   filter(treated=="No") %$% 
   pairw.kw(var1, species, conf = 0.95)

Answer to question in comment:

library(tidyverse)
library(magrittr)
library(asbio)

example.df %>% 
  group_by(treated) %>%
  nest() %>%
  mutate(
    kw = map(
      data,
      ~ .x %$% pairw.kw(var1, species, conf = 0.95)
    ),
    p_val = map_dbl(kw, ~ .x$summary$`Adj. P-value`)
  )