R - 函数类似于使用< = OR> =的Vlookup

时间:2018-04-19 13:52:40

标签: sql r search foreach vlookup

是否存在一个函数,对于dataSet_1中的每个值,在基于多个条件的dataSet_2中进行搜索? 就像在SQL中一样,对于每个值,都要进行新的搜索。

SELECT
value1Table1,
value2Table1,
(
   SELECT MIN(value) FROM table_2 AS table_2
    WHERE table_2.value1 = table_2.value1 AND table_1.Date > table_2.Date 
) AS value1table2, 
value3Table1
FROM table_1

从MAX更改为MIN并且<对于>查询以下示例:

我会尝试解释一下。通常情况下,在我有日期(factDate)和每个用户(具有您自己的不同日期)的情况下,我会使用类似的东西。我需要搜索在factDate之后发生的第一个事件。

示例:

TABLE_1

|User|TargetEventDate|NextEventDate| <- Value that I want
|A   |2018-04-17     |2018-04-18   | <- Value to Find
|B   |2018-04-14     |2018-04-15   | <- Value to Find

TABLE_2

|User|DateEvent |
|A   |2018-04-19|
|A   |2018-04-18| <- Value that I want for user A
|A   |2018-04-17| <- Value used in Table_1 for user A
|A   |2018-04-13|
|A   |2018-03-10|
|B   |2018-04-17|
|B   |2018-04-15| <- Value that I want for user B
|B   |2018-04-14| <- Value user in Table_1 for user B

1 个答案:

答案 0 :(得分:1)

由于相关子查询中的add_filter( 'woocommerce_add_to_cart_validation', 'limit_cart_items_from_category', 10, 3 ); function limit_cart_items_from_category ( $passed, $product_id, $quantity ){ // HERE define your product ID $targeted_product_id = 37; // Check quantity and display notice if( $quantity > 1 && $targeted_product_id == $product_id ){ wc_add_notice( __('Only one item quantity allowed for this product', 'woocommerce' ), 'error' ); return false; } // Loop through cart items checking if the product is already in cart foreach ( WC()->cart->get_cart() as $cart_item ){ if( $targeted_product_id == $product_id && $cart_item['data']->get_id() == $targeted_product_id ) { wc_add_notice( __('This product is already in cart (only one item is allowed).', 'woocommerce' ), 'error' ); return false; } } return $passed; } // Checking and removing quantity field for a specific product add_filter( 'woocommerce_quantity_input_args', 'custom_quantity_input_args', 10, 2 ); function custom_quantity_input_args( $args, $product ) { // HERE define your product ID $targeted_product_id = 37; if( $targeted_product_id == $product->get_id() ) $args['min_value'] = $args['max_value'] = $args['input_value'] = 1; return $args; } 子句,我没有看到将查询重写为更简单的方法的方法。但是,好消息是R有一个名为WHERE的包,它实际上可以执行常规的SQL查询。

sqldf

我在此假设library(sqldf) query <- "SELECT t1.value1Table1, t1.value2Table1, (SELECT MAX(value) FROM table_2 t2 WHERE t1.value1 = t2.value1 AND t1.Date < t2.Date) AS value1table2, t1.value3Table1 FROM table_1" result <- sqldf(query) table_1是实际数据框,其中的列对应于查询所引用的列。