You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中修改阶乘函数将结果存入向量(含while循环)

Solution for Storing Factorial Results in a Vector (Keeping While Loop)

Hey there! Great job on writing that while-loop based factorial function—it works perfectly for single inputs. Now, let's adjust it so we can store multiple results into a vector. I'll show you two practical approaches that keep your original while loop intact:

Approach 1: Auto-Append Results to a Global Vector

If you want to call the function one number at a time and have it automatically add the result to a persistent vector, we can use a global variable. Here's how:

First, initialize an empty vector to hold our results:

factorial_results <- c()

Then modify your existing function to append each new result to this global vector:

factorialcalc <- function(i){ 
  factorial <- 1 
  if(i == 0 | i == 1){ 
    factorial <- 1 
  } else{ 
    while(i >= 1){ 
      factorial <- factorial * i 
      i <- i - 1 
    } 
  }
  # Append the result to our global vector using <<- to modify the global variable
  factorial_results <<- c(factorial_results, factorial)
  return(factorial) 
}

Now when you call the function multiple times:

factorialcalc(5)  # Returns [1] 120
factorialcalc(3)  # Returns [1] 6
factorialcalc(4)  # Returns [1] 24

You can access all stored results by calling the vector:

factorial_results
# Output: [1] 120  6 24

Approach 2: Handle Vector Inputs Directly

A more idiomatic R approach is to let the function accept a vector of numbers and return a corresponding vector of factorials. This avoids global variables and lets you process multiple values in one go:

factorialcalc <- function(nums){
  # Initialize an empty vector to store results
  results <- c()
  
  # Loop through each number in the input vector
  for(num in nums){
    factorial <- 1
    if(num == 0 | num == 1){
      factorial <- 1
    } else {
      i <- num
      while(i >= 1){
        factorial <- factorial * i
        i <- i - 1
      }
    }
    # Add the current factorial to our results vector
    results <- c(results, factorial)
  }
  
  return(results)
}

Use it like this:

# Define your numbers as a vector
mynums <- c(5, 3, 4)
# Get all factorials at once
factorial_results <- factorialcalc(mynums)

# Check the results
factorial_results
# Output: [1] 120  6 24

Both approaches preserve your original while loop logic—we just added layers to handle storing multiple results. The second method is generally preferred in R since it's more self-contained and avoids side effects from global variables.

内容的提问来源于stack exchange,提问作者Delto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:31:10