user1665355
user1665355

Reputation: 3393

Subset a matrix by values in the other matrix

I am trying to subset a matrix :

windowSize <- 60
windows <- embed(1:nrow(datatsr), windowSize)

head(windows):

[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17]   [,18]
[1,]   60   59   58   57   56   55   54   53   52    51    50    49    48    47    46    45    44    43
[2,]   61   60   59   58   57   56   55   54   53    52    51    50    49    48    47    46    45    44
[3,]   62   61   60   59   58   57   56   55   54    53    52    51    50    49    48    47    46    45
[4,]   63   62   61   60   59   58   57   56   55    54    53    52    51    50    49    48    47    46
[5,]   64   63   62   61   60   59   58   57   56    55    54    53    52    51    50    49    48    47
[6,]   65   64   63   62   61   60   59   58   57    56    55    54    53    52    51    50    49    48

dim(windows)
[1] 3291   60

by values (where the V1 column is actually the row numbers I want to include in windows matrix above):

head(subset):

   V1
1  67
2  89
3 111
4 133
5 155
6 176 

dim(subset)
[1] 152   1

range(subset)
[1]   67 3351

I would like the output matrix to only contain the row numbers that are present in column V1 of subset matrix, not the other rows.

In example:

[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17]   [,18]
[1,]  126   125   124   123  122  121   120   119   118    117    116    115    114    113    112    111    110    109

where the first value in subset[,1] is the sequence from 126 to 109 - the sequence that is present in the 67'th row of the windows matrix. And so on...

I tried:

window=windows[subset[,1],]

Error: subscript out of bounds

or:

window=subset(windows,windows%in%subset[,1])

Error in subset.matrix(windows, windows %in% subset[, 1]) : 
(subscript) logical subscript too long

What am I doing wrong?

Upvotes: 0

Views: 1179

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

Remove the values of subset that are higher than the number of rows of windows:

windows[subset$V1[subset$V1 <= nrow(windows)], ]

Upvotes: 2

Related Questions