如何根据第二个数据框中的行是否存在从数据框中删除列?
How to remove columns from dataframe based on whether or not they exist as rows in a 2nd dataframe?
如果以前有人问过我也不会感到惊讶,但在我的搜索中找不到确切的问题。
我的数据由两个数据框组成:
ID = c("patient1", "patient2", "patient3")
phenodf = as.data.frame(ID)
phenodf$status = c("sick", "healthy", "sick")
row.names(phenodf) = phenodf$ID
patient1 = c(1.5, 2.5, 3.5, 4.5)
genes = as.data.frame(patient1)
genes$patient2 = c(2.3, 1.3, 3.3, 4.3)
genes$patient3 = c(3.3, 3.1, 3.4, 3.6)
row.names(genes) = c("ABC", "A2B", "DE5", "ZXY")
#remove healthy patients
phenodf = subset(phenodf, status!=c("healthy"))
现在我需要从 "genes" 数据框中删除健康患者,但这样做的有效方法是什么?
到目前为止,我一直在使用 t(genes)
,合并数据帧以删除不存在于两者中的患者,拆分数据,修复行名称,然后再次使用 t(genes)
-但我相信还有更好的方法!
更新:感谢你们两位,这些想法非常有效,比我一直在做的要好得多!
怎么样:
genes[, colnames(genes) %in% phenodf$ID]
如果以前有人问过我也不会感到惊讶,但在我的搜索中找不到确切的问题。
我的数据由两个数据框组成:
ID = c("patient1", "patient2", "patient3")
phenodf = as.data.frame(ID)
phenodf$status = c("sick", "healthy", "sick")
row.names(phenodf) = phenodf$ID
patient1 = c(1.5, 2.5, 3.5, 4.5)
genes = as.data.frame(patient1)
genes$patient2 = c(2.3, 1.3, 3.3, 4.3)
genes$patient3 = c(3.3, 3.1, 3.4, 3.6)
row.names(genes) = c("ABC", "A2B", "DE5", "ZXY")
#remove healthy patients
phenodf = subset(phenodf, status!=c("healthy"))
现在我需要从 "genes" 数据框中删除健康患者,但这样做的有效方法是什么?
到目前为止,我一直在使用 t(genes)
,合并数据帧以删除不存在于两者中的患者,拆分数据,修复行名称,然后再次使用 t(genes)
-但我相信还有更好的方法!
更新:感谢你们两位,这些想法非常有效,比我一直在做的要好得多!
怎么样:
genes[, colnames(genes) %in% phenodf$ID]