我有一个矩阵,其中包含以下row.names:
"X1" "X5" "X33" "X37" "X52" "X566"
现在我想只选择与列表条目匹配的行,例如:
include_list <- c("X1", "X5", "X33")
我想我会做这样的事情:
data.subset <- subset(data, row.names == include_list)
但是,这个特殊代码似乎没有完成这项工作。如何以这种方式执行子集化?
答案 0 :(得分:26)
设置一些假数据:
m <- matrix(1:30, 6, 5)
rownames(m) <- c("X1", "X5", "X33", "X37", "X52", "X566")
m
# [,1] [,2] [,3] [,4] [,5]
# X1 1 7 13 19 25
# X5 2 8 14 20 26
# X33 3 9 15 21 27
# X37 4 10 16 22 28
# X52 5 11 17 23 29
# X566 6 12 18 24 30
这里使用矩阵索引([
)进行子集可能最简单:
include_list <- c("X1", "X5", "X33")
m[include_list, ]
# [,1] [,2] [,3] [,4] [,5]
# X1 1 7 13 19 25
# X5 2 8 14 20 26
# X33 3 9 15 21 27
替代subset()
函数:
subset(m, rownames(m) %in% include_list)
# [,1] [,2] [,3] [,4] [,5]
# X1 1 7 13 19 25
# X5 2 8 14 20 26
# X33 3 9 15 21 27
答案 1 :(得分:3)
这似乎也有效:
include_list <- head(read.csv("/Users/histelheim/include_list.csv", header = FALSE))
include_list <- c(do.call("cbind", include_list))
data[row.names(data) %in% include_list, ]
答案 2 :(得分:0)
只要某人的 include_list 是类 list (而不是矢量),那么这是Rich Scriven答案的修改,在这种情况下基于{{3} }。 unlist()
应该添加:
m <- matrix(1:30, 6, 5)
rownames(m) <- c("X1", "X5", "X33", "X37", "X52", "X566")
include_list <- list("X1", "X5", "X33")
m[unlist(include_list), ]