我一直在研究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")
并保存到嵌套标题中的新列。这是我使用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"
我认为我缺少明显的东西,可能与this有关。任何帮助将不胜感激!
答案 0 :(得分:3)
由于'lookup_lists'是一个命名为unlist
的文件,我们可以将vector
命名为一个NA
,使用它来匹配'old_vectors'中的元素并替换
具有与“ old_vector”中的元素匹配的“键”的值。不匹配的将是na.omit
。使用grep
将其删除,并与“ old_vectors”中的“ Col”元素(使用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"
)连接
:
答案 1 :(得分:2)
它不起作用,因为global $wpdb;
$order_totals = $wpdb->get_results( "SELECT kp_posts.ID FROM kp_posts INNER JOIN kp_postmeta ON ( kp_posts.ID = kp_postmeta.post_id ) WHERE 1=1 AND ( kp_postmeta.meta_key = 'total_sales' ) AND kp_posts.post_type = 'product' AND (kp_posts.post_status = 'publish') GROUP BY kp_posts.ID ORDER BY kp_postmeta.meta_value+0 DESC, kp_posts.post_date DESC LIMIT 0, 16" );
foreach ( $order_totals as $value ) {
$product = wc_get_product( $value->ID );
echo $product->get_title();
}
不能那样工作。要了解会发生什么,将有助于简化您的示例:
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"