【问题标题】:How to separate two values of same variable under same name?如何分隔同名下同一个变量的两个值?
【发布时间】:2019-11-15 01:45:30
【问题描述】:

我有一个这样的数据框:

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

【问题讨论】:

    标签: r join tibble


    【解决方案1】:

    不幸的是,第一个和第二个brother彼此无法区分! R 怎么知道你想以这种方式加入他们,而不是相反?

    我会尝试通过在原始data.frames 中添加“1”和“2”标识符来“删除重复项”。

    我不知道 tidyverse 的语法,但如果你从来没有得到超过两次的重复,你可能想试试

    a <- c("A", "B", "C", "C") 
    a[duplicated(a)] <- paste0(a[duplicated(a)], 2) 
    

    【讨论】:

    • 这两个就像哥哥和弟弟,按照这个顺序。我需要将 1 放在上一个,将 2 放在下一个。
    【解决方案2】:

    使用 dplyr,您可以执行以下操作,添加一个额外的变量 person 以识别 x 中每个组中的每个人,然后通过 xperson 加入:

    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)
    

    返回:

    # A tibble: 4 x 4
    # Groups:   x [3]
      x       person y     z    
      <chr>    <int> <chr> <chr>
    1 mother       1 a     e    
    2 father       1 b     f    
    3 brother      1 c     g    
    4 brother      2 d     h  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多