![](/img/trans.png)
[英]comparing 2 columns in a data-frame and creating a new column in data frame
[英]Comparing two columns in a data frame for matches and from this creating a new data frame that contains the matches
請問你能再幫我一次嗎?
我有一個包含 4 列的數據框,它們是基因符號或我已分配基因符號的等級,如下所示:
mb_rank mb_gene ts_rank ts_gene
[1] 1 BIRCA 1 MYCN
[2] 2 MYCN 2 MOB4
[3] 3 ATXN1 3 ABHD17C
[4] 4 ABHD17C 4 AEBP2
5 etc... for up to 6000 rows in some data sets.
the ts columns are usually a lot longer than the mb columns.
我想安排數據,以便刪除非重復項,從而只留下出現在數據框兩列中的基因,例如
mb_rank mb_gene ts_rank ts_gene
[1] 2 MYCN 1 MYCN
[2] 4 ABHD17C 3 ABHD17C
在這個期望結果的例子中,非重復基因已被刪除,只留下出現在兩個列表中的基因。
我嘗試了很多事情,例如:
`df[df$mb_gene %in% df$ts_gene,]`
但它不起作用,似乎碰巧錯過了一些基因 2)我試圖寫一個IF
function 但我的技能有限。
我希望我已經很好地描述了這一點,但如果我能澄清任何事情,請問,我真的被卡住了。 提前致謝!
在data.frame
中,通常一行是完整的觀察,這意味着其中的所有數據(以某種方式)與 rest 相關。 在調查中,一行是一個人(所有問題)或一個人一個問題。 但是,在您的數據中,您的第一行BIRCA
和MYCN
是完全分開的,這意味着您想要刪除一個而不刪除另一個。 在“數據科學-y”視圖中,這對我來說表明您的數據形狀不正確。
為了做你想做的事,我們需要將它們分成單獨的框架。
df <- read.table(header = TRUE, stringsAsFactors = FALSE, text = "
mb_rank mb_gene ts_rank ts_gene
1 BIRCA 1 MYCN
2 MYCN 2 MOB4
3 ATXN1 3 ABHD17C
4 ABHD17C 4 AEBP2")
df1 <- df[,1:2]
df2 <- df[,3:4]
df1
# mb_rank mb_gene
# 1 1 BIRCA
# 2 2 MYCN
# 3 3 ATXN1
# 4 4 ABHD17C
df2
# ts_rank ts_gene
# 1 1 MYCN
# 2 2 MOB4
# 3 3 ABHD17C
# 4 4 AEBP2
從這里,我們可以使用intersect
來查找共同的基因:
incommon <- intersect(df1$mb_gene, df2$ts_gene)
df1[df1$mb_gene %in% incommon,]
# mb_rank mb_gene
# 2 2 MYCN
# 4 4 ABHD17C
df2[df2$ts_gene %in% incommon,]
# ts_rank ts_gene
# 1 1 MYCN
# 3 3 ABHD17C
如果您 100% 確定每個行中的行數始終相同,那么您只需將它們cbind
在一起:
cbind(
df1[df1$mb_gene %in% incommon,],
df2[df2$ts_gene %in% incommon,]
)
# mb_rank mb_gene ts_rank ts_gene
# 2 2 MYCN 1 MYCN
# 4 4 ABHD17C 3 ABHD17C
但是,如果每個都有不同的數字,那么您將遇到問題。 如果一個的數量是另一個的倍數,你會得到數據的“回收”和警告,但你仍然會得到數據(我認為這是一個錯誤):
cbind(
df1[df1$mb_gene %in% incommon,],
df2
)
# Warning in data.frame(..., check.names = FALSE) :
# row names were found from a short variable and have been discarded
# mb_rank mb_gene ts_rank ts_gene
# 1 2 MYCN 1 MYCN
# 2 4 ABHD17C 2 MOB4
# 3 2 MYCN 3 ABHD17C
# 4 4 ABHD17C 4 AEBP2
但是,如果不是倍數,您只會得到一個錯誤:
cbind(
df1[df1$mb_gene %in% incommon,],
df2[1:3,]
)
# Error in data.frame(..., check.names = FALSE) :
# arguments imply differing number of rows: 2, 3
我建議您考慮這種存儲結構,因為我相信它違背了某些工具對框架行所做的假設。
使用:df_new 是你的新 dataframe。
df_new = df[df['mb_gene'] == df['ts_gene']]
沒有更多細節,很難了解邊緣情況。 無論如何,這聽起來像是一個關系表連接。 你有沒有嘗試過:
d1 = select(df, c(mb_rank, mb_gene))
d2 = select(df, c(ts_rank, ts_gene))
merge(d1, d2, by.x="mb_gene", by.y="ts_gene")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.