我有一个矩阵,其行名称如下:
"X1" "X5" "X33" "X37" "X52" "X566"
现在我想选择与列表条目匹配的行,例如:
include_list <- c("X1", "X5", "X33")
我会这样做:data.subset <- subset(data, row.names == include_list)
然而,这段特定的代码似乎没有完成任务。我该如何以这种方式进行子集筛选?
我有一个矩阵,其行名称如下:
"X1" "X5" "X33" "X37" "X52" "X566"
现在我想选择与列表条目匹配的行,例如:
include_list <- c("X1", "X5", "X33")
我会这样做:data.subset <- subset(data, row.names == include_list)
然而,这段特定的代码似乎没有完成任务。我该如何以这种方式进行子集筛选?
设置一些虚假数据:
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
这种方式似乎也可以:
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, ]
如果某人的include_list是类别为list(而不是vector),那么这是Rich Scriven答案基于this进行修改的版本。应该添加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), ]