如何在R中的4个数据帧之间只保留常用的行名?

时间:2015-05-08 19:14:00

标签: r matrix

我有4个基因数据框,每个数据框的基因名称为行,大约20列样本数据。因此,每个矩阵都有行数(基因):

  • A:10,000个基因
  • B:15,000个基因
  • C:35,000个基因
  • D:12,000个基因

这是我尝试过的,它没有选择9,000个公共行(Genes)的完整列表

Data_A = read.csv("matrix_A.csv");
Data_B = read.csv("matrix_B.csv");
Data_C = read.csv("matrix_C.csv");
Data_D = read.csv("matrix_D.csv");

Expr_A = as.data.frame(t(Data_A[, -c(1:8)]))
Expr_B = as.data.frame(t(Data_B[, -c(1:8)]))
Expr_C = as.data.frame(t(Data_C[, -c(1:8)]))
Expr_D = as.data.frame(t(Data_D[, -c(1:8)]))

commonGenes1 = intersect (rownames(Data_A),rownames(Data_D))
commonGenes2 = intersect (rownames(Data_B),rownames(Data_D))
commonGenes3 = intersect (rownames(Data_C),rownames(Data_D))

Data_A = Data_A[commonGenes1,]
Data_B = Data_B[commonGenes2,]
Data_C = Data_C[commonGenes3,]

它们共有9,000个基因,虽然数据太大我无法在Excel中执行此操作。我用R来处理数据,有没有办法选择R中4个数据帧之间的共同基因?

这里有4个矩阵的例子: http://www.filedropper.com/matrixexample

2 个答案:

答案 0 :(得分:5)

让我们把事情放在一个列表中(如标题所示),这是一种很好的做法。

list_of_data = list(Data_A, Data_B, Data_C, Data_D)
## for demo purposes, you can use
# list_of_data = list(mtcars[1:6, ], mtcars[4:9, ])

# this will get the intersection of the row.names for everything in the list
common_names = Reduce(intersect, lapply(list_of_data, row.names))

list_of_data = lapply(list_of_data, function(x) { x[row.names(x) %in% common_names,] })

感谢@ eipi10更好地筛选列表中每个数据框的行。查看lame for循环的修订历史记录。

答案 1 :(得分:1)

这个怎么样?

# Create some fake data:
set.seed(123)
m1 <- cbind(sample(1:5), round(rnorm(5),2))
m2 <- cbind(sample(1:5), round(rnorm(5),2))
m3 <- cbind(sample(1:5), round(rnorm(5),2))
m4 <- cbind(sample(1:5), round(rnorm(5),2))
rownames(m1) <- LETTERS[sample(1:10, 5)]
rownames(m2) <- LETTERS[sample(1:10, 5)]
rownames(m3) <- LETTERS[sample(1:10, 5)]
rownames(m4) <- LETTERS[sample(1:10, 5)]


ind <- sapply(list(m1,m2,m3), function(x) intersect(rownames(x), rownames(m4)))
mapply(function(x, y) x[rownames(x) %in% y,], x = list(m1,m2,m3), y = ind)
[[1]]
  [,1]  [,2]
A    4  1.24
D    5 -0.11
E    1  0.18

[[2]]
  [,1]  [,2]
E    5  1.22
C    2 -0.56

[[3]]
  [,1]  [,2]
A    2 -0.22
C    1 -0.33