在R中将n×1向量转换为n×8矩阵的更优方法问询
Hey there! I see you've already nailed a working solution with double transposes, but let's make this cleaner and skip those transposes entirely. Here are a couple of efficient approaches (base R + tidyverse) that get you straight to that n×8 boolean matrix you need for your Markov chain state predictions.
First, let's align on consistent inputs (I'll define the stateSpace you referenced since it wasn't explicitly provided):
stateSpace <- paste0("state ", 1:8) temp_vector <- c("state 4", "state 7")
Method 1: Base R with outer() (No Transposes Needed)
The outer() function is made for this kind of element-wise cross-comparison. It takes each element in temp_vector and compares it to every element in stateSpace, building exactly the n×8 matrix you want:
result_matrix <- outer(temp_vector, stateSpace, FUN = "==") print(result_matrix)
Output:
state 1 state 2 state 3 state 4 state 5 state 6 state 7 state 8 [1,] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE [2,] FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
This matches your desired structure perfectly—each row maps to an element in temp_vector, with TRUE marking the matching state position.
Method 2: Tidyverse Approach with purrr::map_dfr()
If you prefer tidyverse syntax, use map_dfr() to iterate over your vector and build rows of comparison results:
library(purrr) result_matrix <- map_dfr(temp_vector, ~ stateSpace == .x) # Convert to base matrix if needed for Markov chain multiplication result_matrix <- as.matrix(result_matrix) print(result_matrix)
Output:
state 1 state 2 state 3 state 4 state 5 state 6 state 7 state 8 [1,] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE [2,] FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
Quick Note on Your Earlier Attempts
- Attempt 1: Direct matrix conversion repeats elements row-wise because R matrices are column-major by default, which didn't fit your state-matching goal.
- Attempt 2: Comparing the vector to a matrix column-wise (instead of cross-comparing all elements) led to all
FALSEvalues, since the comparison direction and dimensions didn't align.
Both new methods avoid transposes entirely, are more readable, and work efficiently even for larger n values.
内容的提问来源于stack exchange,提问作者Kunal

