簡體   English   中英

比較一個 dataframe 中的兩對列以檢測不匹配並在同一行中顯示另一列的值

[英]Compare two pairs of columns from one dataframe to detect mismatches and show the value from another column in the same row

我正在嘗試解決以下問題。 我有一個 dataframe 如下所示:

 id <- c("1", "2", "3", "4")
 ref <- c("A", "G", "C", "T")
 alt <- c("T", "C", "G", "A")
 ref1 <- c("A", "C", "T", "T")
 alt1 <- c("T", "G", "A", "A")
 df <- data.frame(id, ref,  alt, ref1, alt1)

我需要比較 ref/alt 列對中的值,看看它是否與 dataframe 的每一行的 ref1/alt1 值匹配。 如果不匹配,我希望 r 返回同一行的 id 值。 我很難找到一個簡單的代碼來做到這一點,我會很感激一個建議!

提前致謝

dput() output 的df

structure(list(id = c("1", "2", "3", "4"), ref = c("A", "G", 
"C", "T"), alt = c("T", "C", "G", "A"), ref1 = c("A", "C", "T", 
"T"), alt1 = c("T", "G", "A", "A")), class = "data.frame", row.names = c(NA, 
-4L))

您可以使用 ifelse 如下:

library(tidyverse)

matches <- df %>% 
   mutate(check = ifelse(alt==alt1 & ref==ref1, "Yes", "No")) %>% 
   filter(check=="Yes") 

unique(matches$id)

一個tidyverse的解決方案。

libary(tidyverse)

df %>% 
  mutate(ref_check = ref == ref1,
         alt_check = alt == alt1,
         both_ceck = ref_check & alt_check) %>% 
  filter(!both_ceck) %>% 
  pull(id)

和一個base R解決方案。

df[df$ref != df$ref1 & df$alt != df$alt1, ]$id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM