如何用相同的名称分隔相同变量的两个值?

时间:2019-07-04 10:23:41

标签: r join tibble

我有一个这样的数据框:

library(tidyverse)
a <- tibble(x=c("mother","father","brother","brother"),y=c("a","b","c","d"))
b <- tibble(x=c("mother","father","brother","brother"),z=c("e","f","g","h"))

我想加入这些数据框,以便每个“兄弟”只出现一次

我尝试了完全加入

 ab <- full_join(a,b,by="x")

并获得了此信息:

    # A tibble: 6 x 3
  x       y     z    
  <chr>   <chr> <chr>
1 mother  a     e    
2 father  b     f    
3 brother c     g    
4 brother c     h    
5 brother d     g    
6 brother d     h 

我需要的是这个

ab <- tibble(x=c("mother","father","brother1","brother2"),y=c("a","b","c","d"),z=c("e","f","g","h"))

# A tibble: 4 x 3
  x        y     z    
  <chr>    <chr> <chr>
1 mother   a     e    
2 father   b     f    
3 brother1 c     g    
4 brother2 d     h

2 个答案:

答案 0 :(得分:2)

使用dplyr,您可以执行以下操作,该操作添加了一个额外的变量person以标识x中每个组中的每个人,然后通过x和{{1 }}:

person

哪个返回:

library(dplyr)

a %>% 
    group_by(x) %>% 
    mutate(person = 1:n()) %>%
    full_join(b %>% 
                  group_by(x) %>%
                  mutate(person = 1:n()),
              by = c("x", "person")
              ) %>% 
    select(x, person, y, z)

答案 1 :(得分:1)

不幸的是,第一个brother和第二个data.frame彼此难以区分! R如何知道您想以这种方式加入他们,而不是相反?

我会尝试通过在原始a <- c("A", "B", "C", "C") a[duplicated(a)] <- paste0(a[duplicated(a)], 2) 中添加“ 1”和“ 2”标识符来“删除重复项”。

我不知道tidyverse语法,但是如果您从未获得两次以上的重复,则不妨尝试一下

//** Custom code**//
                /* OLD CODE*/
                //find first the product_id

                //$items = $order->get_items();
                 //foreach ( $items as $item ) {
                    //$product_id = $item['product_id'];
                //}

                /*NEW CODE*/
                // Iterating through each WC_Order_Item_Product objects
            $items = $order->get_items();
            foreach ($items as $item ) {
                    // Item ID is directly accessible from the $item_key in the foreach loop or
                $product = wc_get_product($item['product_id']);

                $patt = $product->get_attributes();
            }

                if ( array_key_exists('pa_csr-dates' , $patt)) 
                {
                    $trigger = true;


                }

                if ( $this->is_enabled() && $this->get_recipient() && $trigger === true) {
                    $this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
                }
                else {return;}