Find a vector in matrix when order matters in R -
i have matrix m
follows:
> m [,1] [,2] [,3] [,4] [,5] [1,] 4 1 5 2 3 [2,] 5 2 3 4 1 [3,] 3 4 1 5 2 [4,] 1 5 2 3 4 [5,] 2 3 4 1 5 [6,] 4 1 5 2 3 [7,] 5 2 3 4 1 [8,] 3 4 1 5 2
and vector named vec
follows:
> vec [1] 3 1
i'd find rows in m
containing vec
in same order. e.g. result should (note first, fourth , sixth rows not of interest):
> res [2,] 5 2 3 4 1 [3,] 3 4 1 5 2 [5,] 2 3 4 1 5 [7,] 5 2 3 4 1 [8,] 3 4 1 5 2
would please tell me how can in r? thanks
here's general solution. can create regex pattern vec
check against data combined set of strings each row:
v2 <- paste(vec, collapse=".*?") df.vec <- do.call(paste, as.data.frame(m)) m[grep(v2, df.vec),] # [,1] [,2] [,3] [,4] [,5] # [2,] 5 2 3 4 1 # [3,] 3 4 1 5 2 # [5,] 2 3 4 1 5 # [7,] 5 2 3 4 1 # [8,] 3 4 1 5 2
Comments
Post a Comment