基于坐标提取矩阵数据:R语言按行列标识定位单元格需求
Got it, let's work through this problem step by step. Here's how to make R recognize your {row, col} notation and pull the correct matrix cell values:
1. First, Combine Your Row Variables into a Single Matrix
Since you already have individual row vectors (r010, r020, ..., r990), let's bundle them into a proper matrix with matching column names:
# Bind all row vectors into a matrix (matches pattern r followed by 3 digits) my_matrix <- do.call(rbind, mget(ls(pattern = "^r\\d{3}$"))) # Set column names to c010, c020, ..., c990 colnames(my_matrix) <- paste0("c", sprintf("%03d", seq(10, 990, 10)))
This creates a 99x99 matrix where each row corresponds to your rXXX variables, and columns are labeled with your cXXX naming convention.
2. Build a Helper Function to Fetch Cell Values
To translate {r010, c070} into the correct cell, we'll create a function that maps the r/c names to row/column indices. From your description, r010 = row 1, c070 = column 7—so we extract the middle two digits from the r/c string and convert to an integer:
cell <- function(row_vec, col_label) { # Get the name of the row variable (e.g., "r010" from r010) row_name <- deparse(substitute(row_vec)) # Extract row index: take digits 2-3 from row_name, convert to integer row_idx <- as.integer(substr(row_name, 2, 3)) # Extract column index: take digits 2-3 from col_label, convert to integer col_idx <- as.integer(substr(col_label, 2, 3)) # Return the matrix cell value my_matrix[row_idx, col_idx] }
How to Use It:
Instead of writing {r010, c070}, you can call the function directly:
# Get value from row 1, column 7 cell(r010, "c070") # Test your example expression cell(r010, "c070") + cell(r020, "c070") == cell(r030, "c090")
3. Parse Full Expression Strings (Optional)
If you have entire expression strings like "{r010, c070} + {r020, c070} == {r030, c090}", we can automate the parsing and evaluation:
evaluate_expr <- function(expr_str) { # Replace {rXXX, cXXX} with cell(rXXX, "cXXX") parsed_str <- gsub("\\{(r\\d{3}),\\s*(c\\d{3})\\}", "cell(\\1, \"\\2\")", expr_str) # Evaluate the parsed expression eval(parse(text = parsed_str)) }
Example Usage:
# Test the sample expression evaluate_expr("{r010, c070} + {r020, c070} == {r030, c090}")
This will return TRUE or FALSE based on whether the equation holds for your matrix values.
内容的提问来源于stack exchange,提问作者Sven

