R语言三维数组中匹配指定向量的索引获取方法
For a specific given i
If you have a particular value of i (say i = 42), you can find the matching j by checking each of the 5 slices against V using identical():
# Example: given i = 42 i <- 42 j_match <- which(sapply(1:5, function(j) identical(h[i, j, ], V)))
Since the problem states there's exactly one match per i, j_match will be a single integer between 1 and 5.
Get all (i,j) pairs that match V
To find every combination of i (1-100) and j (1-5) where the 9-element slice matches V, you can use a straightforward approach with expand.grid and sapply:
# Create all possible (i,j) pairs all_pairs <- expand.grid(i = 1:100, j = 1:5) # Filter pairs where the slice matches V exactly matching_pairs <- all_pairs[ sapply(1:nrow(all_pairs), function(k) { identical(h[all_pairs$i[k], all_pairs$j[k], ], V) }), ]
The result matching_pairs is a data frame with columns i and j, containing all index pairs where the slice matches V.
Alternative vectorized approach (better for larger datasets)
If you ever work with bigger arrays later, reshaping the 3D array into a 2D matrix can speed up the matching process:
# Reshape 3D array into a 2D matrix (each row = a 9-element sequence) h_matrix <- matrix(h, nrow = 100 * 5, ncol = 9) # Find rows that match V exactly matching_rows <- which(apply(h_matrix, 1, function(row) identical(row, V))) # Convert row indices back to (i,j) pairs i_vals <- ceiling(matching_rows / 5) j_vals <- ifelse(matching_rows %% 5 == 0, 5, matching_rows %% 5) matching_pairs <- data.frame(i = i_vals, j = j_vals)
This works because each i corresponds to 5 consecutive rows in the matrix (j=1 to 5). The modulo operation gives us the j index, with a quick adjustment for when the row number is a multiple of 5 (since 5 mod 5 is 0, we replace that with 5).
All these methods rely on identical(), which ensures an exact match (including data type and structure) just as you specified.
内容的提问来源于stack exchange,提问作者ChuckP

