如何通过purrr :: pmap将参数从小标题正确地传递到函数中

时间:2019-07-23 04:25:43

标签: r tidyverse purrr

我具有以下功能,它只是串联了一系列字符串

test_func <- function(cellTypeA, cellTypeB, other_text) { 
   paste(cellTypeA, " ", cellTypeB, " ", other_text)
}

我有一组参数打包成小标题。

param_df <- structure(list(cellTypeA = c("Cluster11", "Cluster2", "Cluster4"
), cellTypeB = c("Cluster11", "Cluster2", "Cluster4")), row.names = c(NA, 
-3L), class = "data.frame")

看起来像这样:

  cellTypeA cellTypeB
1 Cluster11 Cluster11
2  Cluster2  Cluster2
3  Cluster4  Cluster4

我想使用purrr :: pmap对上面设置的参数进行迭代。但是为什么这不起作用?

library(tidyverse)
param_df %>%
 pmap(~test_func(.cellTypeA, .cellTypeB, "FOO"))

它给了我:

Error in cat(cellTypeA, " ", cellTypeB) : object '.cellTypeA' not found 

我希望结果看起来像这样:

[[1]]
[1] Cluster11 Cluster11 FOO

[[2]]
[1] Cluster2  Cluster2 FOO

[[3]]
[1] Cluster4  Cluster4 FOO

2 个答案:

答案 0 :(得分:1)

cat()是错误的功能。它只是打印到控制台。这是一种选择:

test_func <- function(cellTypeA, cellTypeB, other_text) { 
                paste(cellTypeA, " ", cellTypeB, " ", other_text)
  }

pmap(param_df, ~data.frame(string = test_func(..., "FOO")))

[[1]]
                       string
1 Cluster11   Cluster11   FOO

[[2]]
                     string
1 Cluster2   Cluster2   FOO

[[3]]
                     string
1 Cluster4   Cluster4   FOO

答案 1 :(得分:0)

对于pmap,您将使用.x返回到输入列表(或数据框)的两列。和.y。因此代码将是:

param_df %>%
  pmap(~test_func(.x, .y, other_text="FOO"))
[[1]]
[1] "Cluster11   Cluster11   FOO"

[[2]]
[1] "Cluster2   Cluster2   FOO"

[[3]]
[1] "Cluster4   Cluster4   FOO"

您还可以使用数字返回到输入列,如果您有两列以上的参数,这将很有帮助。例如:

test_func2 <- function(col1, col2, col3, other_text) { 
  paste(col1, col2, col3, other_text)
}

param_df %>%
  mutate(cellTypeC = paste0("Cluster", 10:12)) %>% 
  pmap(~test_func2(..1, ..2, ..3, other_text="FOO"))
[[1]]
[1] "Cluster11 Cluster11 Cluster10 FOO"

[[2]]
[1] "Cluster2 Cluster2 Cluster11 FOO"

[[3]]
[1] "Cluster4 Cluster4 Cluster12 FOO"

如果您希望能够传递任意数量的列作为参数,则可以将函数概括如下:

test_func3 <- function(..., other_text) { 
  paste(paste(..., sep=" "), other_text, sep=" ")
}

param_df %>%
  pmap(~test_func3(..., other_text="FOO"))
[[1]]
[1] "Cluster11   Cluster11   FOO"

[[2]]
[1] "Cluster2   Cluster2   FOO"

[[3]]
[1] "Cluster4   Cluster4   FOO"
iris[1:2, ] %>%
  pmap(~test_func3(..., other_text="FOO"))
[[1]]
[1] "5.1 3.5 1.4 0.2 setosa FOO"

[[2]]
[1] "4.9 3 1.4 0.2 setosa FOO"