如何在R语言中查找一个向量在另一个向量中的首次出现位置?
Great question! You're right that which() and match() only handle single-element matches—they don't work for finding a contiguous sequence of elements like your x1 in x2.
R's base package doesn't have a built-in function specifically for this exact task, but it's straightforward to build your own, or use functions from third-party packages if you prefer. Here are a couple of approaches:
1. Custom Function (Base R, No Packages Needed)
This function checks every valid starting position in x2 where x1 could fit, and returns the first match it finds:
find_first_sequence_match <- function(pattern, text) { pattern_len <- length(pattern) text_len <- length(text) # Calculate all valid starting positions (avoids going out of bounds) possible_starts <- seq_len(text_len - pattern_len + 1) # Loop through each position to check for a full match for (start in possible_starts) { window <- text[start:(start + pattern_len - 1)] if (all(window == pattern)) { return(start) } } # Return NA if no match exists return(NA) }
Test it with your example:
x1 <- c(0,1,2) x2 <- c(1,2,0,1,2,3,4,5,0,1,0,1,2) find_first_sequence_match(x1, x2) # Output: 3
2. Using a Third-Party Package (zoo)
If you don't mind using an external package, the rollapply() function from the zoo package creates sliding windows over x2 to check for matches:
library(zoo) # Create sliding windows matching x1's length, check for full matches matches <- rollapply(x2, length(x1), function(window) all(window == x1)) # Grab the first matching position first_match_pos <- which(matches)[1] first_match_pos # Output: 3
Either approach will reliably return the first starting position of your target sequence.
内容的提问来源于stack exchange,提问作者Zofhd

