[英]Named list issue when using dplyr::recode within purrr::map2
我一直在努力通過R purrr包,我遇到了障礙。 我在下面創建了一些模擬數據,它代表了我的數據實際上看起來非常小的片段。
library(tidyverse)
my_data <- tribble(
~lookup_lists, ~old_vectors,
# Observation 1
list(
"X1" = "one",
"X7" = "two",
"X16" = "three"
),
c("Col1", "Col2", "Col3", "X1", "X7", "X16"),
# Observation 2
list(
"X3" = "one",
"X8" = "two",
"X22" = "three"
),
c("Col1", "Col2", "Col3", "X3", "X8", "X22")
)
此時,我想創建一個與old_vectors
具有相同向量值的新列,但是以X開頭的值將被重新編碼以反映lookup_lists
的查找命名列表。 例如,我希望第一行來自:
c("Col1", "Col2", "Col3", "X1", "X7", "X16")
至
c("Col1", "Col2", "Col3", "one", "two", "three")
並保存到嵌套tibble中的新列。 這是我嘗試使用map2
函數:
# Add a third column that has the recoded vectors
my_data <- my_data %>%
mutate(new_vectors = map2(.x = old_vectors, .y = lookup_lists, .f = ~recode(.x, .y)))
#> Error in mutate_impl(.data, dots): Evaluation error: Argument 2 must be named, not unnamed.
我不明白這個,因為第二個參數是IS命名的。 這是第一個觀察的lookup_list來表明我的觀點:
my_data$lookup_lists[[1]]
$X1
[1] "one"
$X7
[1] "two"
$X16
[1] "three"
我想我錯過了一些非常明顯的東西,可能與此有關 。 任何幫助將不勝感激!
由於'lookup_lists'是一個命名list
,我們可以unlist
其unlist
list
到命名vector
,使用它來匹配'old_vectors'中的元素,並將'key'與'old_vector'中的元素匹配的值替換。 那些不匹配的將是NA
。 使用na.omit
刪除它並與'old_vectors'中的'Col'元素(使用grep
)連接
out <- my_data %>%
mutate(new_vectors = map2(old_vectors, lookup_lists,
~ c(grep('Col', .x, value = TRUE), unname(na.omit(unlist(.y)[.x])))))
out$new_vectors
#[[1]]
#[1] "Col1" "Col2" "Col3" "one" "two" "three"
#[[2]]
#[1] "Col1" "Col2" "Col3" "one" "two" "three"
它不起作用,因為recode
不起作用。 要了解發生了什么,有助於簡化您的示例:
x <- my_data[["old_vectors"]]
y <- my_data[["lookup_lists"]]
recode(x[[1]], y[[1]])
## Error: Argument 2 must be named, not unnamed
如?recode
,該函數不需要命名的替換列表,而是一系列命名參數。 也就是說,而不是它想要的recode(x[[1]], y[[1]])
recode(x[[1]], X1 = "one", X7 = "two", X16 = "three")
## [1] "Col1" "Col2" "Col3" "one" "two" "three"
這種情況很常見,有一種標准方法:
invoke(recode, .x = y[[1]], x[[1]])
## [1] "Col1" "Col2" "Col3" "one" "two" "three"
現在我們知道如何將一個命名的參數列表傳遞給一個需要多個(可能是命名的)參數的函數,我們可以運用這些知識來解決原始問題:
my_data <- my_data %>%
mutate(new_vectors = map2(.x = old_vectors, .y = lookup_lists,
.f = ~invoke(recode, .x = .y, .x)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.