【问题标题】:Merging sets of data frame columns合并数据框列集
【发布时间】:2019-06-20 06:48:52
【问题描述】:

可能是一个简单的。

我有这种类型的data.frame:

df <- data.frame(sp1.name = c("sp1.n1",NA,"sp1.n3",NA), sp1.id = c("sp1.id1","sp1.id2",NA,NA),
                 sp2.name = c(NA,NA,"sp2.n3",NA), sp2.id = c(NA,NA,NA,"sp2.id4"),
                 sp3.name = c("sp3.n1",NA,NA,NA), sp3.id = c("sp3.id1",NA,NA,NA))

它由每个“sp”索引的列对组成:sp&lt;index&gt;.name 和 sp&lt;index&gt;.id。在此示例中,索引为 1,2,3。

我正在寻找一种方法(可能通过tidyverse)来合并,对于每个sp,它的一对对应的名称和id列合并规则是:

  1. if !is.na(sp&lt;index&gt;.name) &amp; !is.na(sp&lt;index&gt;.id) return sp&lt;index&gt;.name
  2. if !is.na(sp&lt;index&gt;.name) &amp; is.na(sp&lt;index&gt;.id) return sp&lt;index&gt;.name
  3. else if is.na(sp&lt;index&gt;.name) &amp; !is.na(sp&lt;index&gt;.id) return sp&lt;index&gt;.id
  4. else return NA

所以对于这个例子,data.frame 是:

df <- data.frame(sp1 = c("sp1.n1","sp1.id2","sp1.n3",NA),
                 sp2 = c(NA,NA,"sp2.n3","sp2.id4"),
                 sp3 = c("sp3.n1",NA,NA,NA))

【问题讨论】:

    标签: r dataframe dplyr tidyverse tidyr


    【解决方案1】:

    你可以这样做:

    library(tidyverse)
    
    df %>%
      mutate(rn = row_number()) %>%
      gather(id, value, -rn) %>%
      mutate(idx = gsub("\\..*", "", id)) %>%
      group_by(idx, rn) %>%
      mutate(
        value = case_when(
          any(grepl("name", id) & !is.na(value)) & any( (grepl("id", id) & !is.na(value)) | (grepl("id", id) & is.na(value)) ) ~ value[grepl("name", id)],
          any(grepl("name", id) & is.na(value)) & any(grepl("id", id) & !is.na(value)) ~ value[grepl("id", id)],
          TRUE ~ NA_character_)) %>% 
      distinct(idx, value, rn) %>%
      spread(idx, value)
    

    给予:

    # A tibble: 4 x 4
    # Groups:   rn [4]
         rn sp1     sp2     sp3   
      <int> <chr>   <chr>   <chr> 
    1     1 sp1.n1  NA      sp3.n1
    2     2 sp1.id2 NA      NA    
    3     3 sp1.n3  sp2.n3  NA    
    4     4 NA      sp2.id4 NA    
    

    【讨论】:

      猜你喜欢
      • 2018-02-24
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 2016-06-25
      • 2018-12-31
      • 1970-01-01
      相关资源
      最近更新 更多