如何为函数传入参数以返回多值结果?关于isingLenzMC包中transitionProbability1D函数仅返回单个数值的技术问询
transitionProbability1D Returns a Single Value Instead of a Vector It looks like the core issue here is that the transitionProbability1D function from the isingLenzMC package isn't designed to handle vectorized inputs for parameters like bF by default. Most custom R functions (especially those in niche packages) only process scalar values unless explicitly built with vectorization in mind. When you pass a vector for bF, the function likely only evaluates the first element (or collapses the vector in an unintended way) and returns a single result.
How to Get a Vector of Results
To compute the transition probability for each value in your bF vector, you need to iterate over each element and call the function individually. Here are a few straightforward ways to do this:
1. Use sapply (Simplest Approach)
Sapply will loop through each value in bF, run the function, and return a vector of results:
N <- 100 conf0 <- genConfig1D(N) conf1 <- flipConfig1D(conf0) bF <- 1:10 J <- h <- 1 # Adjust to scalar if the function expects single values for J/h # Use sapply to iterate over each bF value prob_vector <- sapply(bF, function(b) { transitionProbability1D(b, conf0, conf1, J, h, 1) }) prob_vector
2. For Loop (More Explicit)
If you prefer a transparent, step-by-step loop structure:
prob_vector <- numeric(length(bF)) # Initialize empty vector to store results for (i in seq_along(bF)) { prob_vector[i] <- transitionProbability1D(bF[i], conf0, conf1, J, h, 1) } prob_vector
3. Verify Function Vectorization Support
Before implementing workarounds, double-check if the function supports vectorized inputs natively. Run this to view its documentation:
?transitionProbability1D
Look at the parameter descriptions for bF, J, and h. If the docs state these parameters accept vectors, there might be a mismatch in how you're passing other arguments. But based on your example, it's safe to assume vectorization isn't supported out of the box.
Quick Note on J and h
You originally set J <- h <- rep(1,10) as vectors. If the function expects scalar values for coupling constants (J) and external fields (h), adjust these to single values (like J <- 1, h <- 1) unless you're intentionally using position-specific constants/fields.
内容的提问来源于stack exchange,提问作者user13696679

