【问题标题】:How to create new columns in a data.frame based on row values in R?如何根据 R 中的行值在 data.frame 中创建新列?
【发布时间】:2019-11-18 08:00:28
【问题描述】:

嘿嘿,

我有一个包含家庭三重奏的 data.frame,我想添加一列,其中包含每个“id”(=后代)的完整同胞。

我的数据:

df
         id    dam    sire
1:    83295  67606   79199
2:    83297  67606   79199
3:    89826  67606   79199

我要检索的内容:

df2
         id    dam    sire     fs1     fs2
1:    83295  67606   79199   83297   89826  
2:    83297  67606   79199   83295   89826  
3:    89826  67606   79199   83295   83297  

我尝试过的:

(类似于:How to transform a dataframes row into columns in R?)

library(dplyr)
library(splitstackshape)

df2 <- df %>%
  group_by(dam,sire) %>%
  summarise(id = toString(id)) %>%
  cSplit("id") %>%
  setNames(paste0("fs_", 1:ncol(.)))

colnames(df2) <- c("dam", "sire", "id", "fs1", "fs2")

每个父二人组只给我一行(而不是为每个“id”创建同一行):

df2
     dam    sire       id      fs1     fs2
1: 67606   79199    83295    83297    89826  

在某些情况下不会有完整的同胞,在某些情况下会有 15 个。

提前感谢您的建议! :)

【问题讨论】:

    标签: r dplyr transformation splitstackshape


    【解决方案1】:

    我们可以使用setdiff group_by dam 和 sire 获取除当前 id 之外的所有 id's,然后使用 cSplit 将逗号分隔的值分隔到不同的列中。

    library(splitstackshape)
    library(dplyr)
    
    df %>%
      group_by(dam, sire) %>%
      mutate(fs = purrr::map_chr(id, ~toString(setdiff(id, .x)))) %>%
      cSplit("fs")
    
    #      id   dam  sire  fs_1  fs_2
    #1: 83295 67606 79199 83297 89826
    #2: 83297 67606 79199 83295 89826
    #3: 89826 67606 79199 83295 83297
    

    数据

    df <- structure(list(id = c(83295L, 83297L, 89826L), dam = c(67606L, 
    67606L, 67606L), sire = c(79199L, 79199L, 79199L)), class = "data.frame",
    row.names = c("1:", "2:", "3:"))
    

    【讨论】:

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