Liz Wimborne
Liz Wimborne

Reputation: 11

When applying function to dataframe error that column is htest object and that all columns in tibble must be vectors

I am trying to run function

growth<- function(x){
  cor.test(df3$H1, x, method = "spearman", exact = FALSE)
}

v1<-map_dfr(df3, growth)

where str(df3) shows all to be numerical. When I run this however it says

Error: All columns in a tibble must be vectors.
x Column H1 is a htest object.
x Column laz_12 is a htest object.
x Column waz_12 is a htest object.
x Column hcz_12 is a htest object.
x Column maz_12 is a htest object.
x ... and 4 more problems.

Upvotes: 1

Views: 774

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389325

For map_dfr to work the output from the function needs to be dataframe or tibble. Output from growth function is an htest object. Probably you can tidy the output to return a tibble.

Here's an example with mtcars dataset.

growth<- function(x){ 
    broom::tidy(cor.test(mtcars$mpg, x, method = "spearman", exact = FALSE)) 
}

v1 <- purrr::map_dfr(mtcars, growth, .id = "col")
v1

#   col   estimate statistic  p.value method                        alternative
#   <chr>    <dbl>     <dbl>    <dbl> <chr>                           <chr>      
# 1 mpg      1            0  0        Spearman's rank correlation rho two.sided  
# 2 cyl     -0.911    10425. 4.69e-13 Spearman's rank correlation rho two.sided  
# 3 disp    -0.909    10415. 6.37e-13 Spearman's rank correlation rho two.sided  
# 4 hp      -0.895    10337. 5.09e-12 Spearman's rank correlation rho two.sided  
# 5 drat     0.651     1902. 5.38e- 5 Spearman's rank correlation rho two.sided  
# 6 wt      -0.886    10292. 1.49e-11 Spearman's rank correlation rho two.sided  
# 7 qsec     0.467     2908. 7.06e- 3 Spearman's rank correlation rho two.sided  
# 8 vs       0.707     1601. 6.19e- 6 Spearman's rank correlation rho two.sided  
# 9 am       0.562     2390. 8.16e- 4 Spearman's rank correlation rho two.sided  
#10 gear     0.543     2495. 1.33e- 3 Spearman's rank correlation rho two.sided  
#11 carb    -0.657     9043. 4.34e- 5 Spearman's rank correlation rho two.sided  

Upvotes: 1

Related Questions