[英]How to create new columns in a data.frame based on row values in R?
嘿嘿,
我有一個帶有家庭三重奏的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 個。
提前感謝您的建議::)
我們可以group_by
dam
和setdiff
使用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:"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.