Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

r - Subsetting a matrix by row.names

I have a matrix with the following row.names:

"X1"   "X5"   "X33"  "X37"  "X52"  "X566"

Now I want to select only the rows which match the entries of a list, say:

include_list <- c("X1", "X5", "X33")

I imagine I'd do something like this:

data.subset <- subset(data, row.names == include_list)

However, this particular code does not seem to do the job. How can I perform subsetting in this way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Set up some fake data:

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

Here it's probably easiest to subset with matrix indexing ([):

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

Alternative with subset() function:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...