R语言函数返回矩阵与向量的访问问题求助
place() Function Hey there! Let's sort out this issue you're facing with retrieving the returned values from your place() function. The root problem here is how you're returning the board and av_targets right now—using c(board, av_targets) flattens your 10x10 matrix into a one-dimensional vector, then concatenates it with av_targets into a single long vector. That's why v[2] gives you the second element of the original matrix instead of the av_targets vector you want.
The Solution: Use a List to Return Multiple Objects
In R, if you want to return multiple distinct objects (like a matrix and a vector, just like you do with tuples in Python), you need to wrap them in a list. Lists can hold different types and dimensions of data without flattening them, which is exactly what you need here.
Modified place() Function
Here's how to adjust your function to return a list instead:
place <- function(ship, orientation, location, board, av_targets){ if (orientation[1] == -1){ for (i in 0:(as.integer(ships_dim[ship])-1)){ board[location[1], location[2]+(i*as.integer(orientation[2]))] <- keys[ship] av_targets <- av_targets[av_targets != paste0(location[1], location[2])] } } if (orientation[1] == 1){ for (i in 0:(as.integer(ships_dim[ship])-1)){ board[location[1]+(i*as.integer(orientation[2])), location[2]] <- keys[ship] av_targets <- av_targets[av_targets != paste0(location[1], location[2])] } } # Return as a named list for clear access return(list(board = board, av_targets = av_targets)) }
Accessing the Returned Values
Now when you call the function:
v <- place("destroyer", c(1,1), c(4,4), computer_board, computer_av_targets)
You can access the values in two ways, similar to Python:
- Named access (recommended for readability):
- Get the updated matrix:
v$board - Get the updated target vector:
v$av_targets
- Get the updated matrix:
- Index-based access (like Python's
v[0]/v[1], but R uses 1-based indexing):- Get the matrix:
v[[1]](use double brackets to extract the actual matrix, not a sub-list) - Get the vector:
v[[2]]
- Get the matrix:
Why This Works
Unlike c(), which coerces all inputs to the same type (flattening your matrix in the process), lists preserve the original structure of each object. This means your 10x10 matrix stays a matrix, and your av_targets vector stays a vector—no more mixing them into a single flat vector.
内容的提问来源于stack exchange,提问作者lambda

