簡體   English   中英

如果分類變量的頻率低於定義的值,則使用R重新編碼變量

[英]R to recode variables if the categorical variable's frequency lower than an defined value

這是數據集(d)的示例:

rs3 rs4 rs5 rs6
1   0   0   0
1   0   1   0
0   0   0   0
2   0   1   0
0   0   0   0
0   2   0   1
0   2   NA  1
0   2   2   1
NA  1   2   1

要檢查SNP基因型(0,1,2)的頻率,我們可以使用table命令

table (d$rs3)

輸出將是

0 1 2 
5 2 1

如果基因型2的頻率<3,我們想在這里重新編碼變量,重新編碼后的輸出應該是

rs3 rs4 rs5 rs6
1   0   0   0
1   0   1   0
0   0   0   0
1   0   1   0
0   0   0   0
0   2   0   1
0   2   NA  1
0   2   1   1
NA  1   1   1

我有70000個SNP需要檢查和重新編碼。 如何在R中使用for循環或其他方法執行此操作?

這是另一個可能的(矢量化)解決方案

indx <- colSums(d == 2, na.rm = TRUE) < 3 # Select columns by condition
d[indx][d[indx] == 2] <- 1 # Inset 1 when the subset by condition equals 2
d
#   rs3 rs4 rs5 rs6
# 1   1   0   0   0
# 2   1   0   1   0
# 3   0   0   0   0
# 4   1   0   1   0
# 5   0   0   0   0
# 6   0   2   0   1
# 7   0   2  NA   1
# 8   0   2   1   1
# 9  NA   1   1   1

我們可以試試

 d[] <- lapply(d, function(x) 
    if(sum(x==2, na.rm=TRUE) < 3) replace(x, x==2, 1) else x)
d
#   rs3 rs4 rs5 rs6
#1   1   0   0   0
#2   1   0   1   0
#3   0   0   0   0
#4   1   0   1   0
#5   0   0   0   0
#6   0   2   0   1
#7   0   2  NA   1
#8   0   2   1   1
#9  NA   1   1   1

或者可以在dplyr使用相同的方法

library(dplyr)
d %>%
    mutate_each(funs(if(sum(.==2, na.rm=TRUE) <3) 
                replace(., .==2, 1) else .))

暫無
暫無

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

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