管道操作结束时的相关性

correlation at the end of a pipe operation

我试图在管道操作结束时获得两个变量之间的相关性,为什么这些不起作用?

library(tidyverse)
iris %>% 
  map(~cor(.$Sepal.Length, .$Sepal.Width, use = "complete.obs"))

#or
iris %>% 
  dplyr::select(Sepal.Length, Sepal.Width) %>% 
  map2(~cor(.x, .y, use = "complete.obs"))

谢谢

它不需要 map,因为这可以在 summarise

内完成
library(dplyr)
iris %>% 
  summarise(out = cor(Sepal.Length, Sepal.Width, use = "complete.obs"))
#       out
#1 -0.1175698

使用 map2,执行的任务是对相关列的每个对应元素应用一个函数,其中 cor 是在作为一个单元的完整列上

第二个选项与

类似
Map(cor, iris$Sepal.Length, iris$Sepal.Width,
        MoreArgs = list(use = 'complete.obs'))

iris %>% 
  dplyr::select(Sepal.Length, Sepal.Width) %>% 
  {map2(.$Sepal.Length, .$Sepal.Width, .f = cor, use = "complete.obs")}

pmap

iris %>%
   dplyr::select(Sepal.Length, Sepal.Width) %>% 
   pmap(~ cor(.x, .y, use = "complete.obs"))

注意:所有这些 returns NA 因为观察的数量是 1

mapmap2 用于迭代 - 你不想迭代任何东西,你只想在两列上调用 cor。我建议

iris %>%
  with(cor(Sepal.Length, Sepal.Width, use = "complete.obs"))

别忘了 %$% !

library(magrittr)

iris %$% 
  cor(Sepal.Length, Sepal.Width, use = "complete.obs")
#> [1] -0.1175698

reprex package (v0.3.0)

于 2021 年 3 月 2 日创建

感谢@akrun,我记得这可能也有效,请参阅

iris %>%    
  {(cor(.$Sepal.Length, .$Sepal.Width, use = "complete.obs"))}