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

如何将三个已创建的R语言函数向量合并为一个生成函数?

Unified R Vector Generator Function

Got it, let's merge your three separate R vector functions into a single, versatile tool that can handle all three use cases. Here's a clean implementation that stays true to your original code's behavior:

vector_generator <- function(type = c("numeric", "character", "logical")) {
  # Validate and match the input type to valid options
  type <- match.arg(type)
  
  # Use switch to handle different vector types
  switch(type,
         numeric = sample(1:20, 5, replace = FALSE),
         character = sample(letters[1:26], 5, replace = FALSE),
         logical = {
           # Replicate the original logical vector generation logic
           x <- c(1:20, 1:10 == TRUE)
           as.logical(sample(x, 5, replace = FALSE))
         })
}

How It Works

  • Parameter type: This lets you specify which kind of vector you want to generate. Valid options are "numeric", "character", or "logical". If you don't specify a type, it defaults to "numeric".
  • match.arg(type): Ensures the input type is one of the valid options—if someone enters an invalid value (like "string"), it'll throw a clear error instead of failing silently.
  • Switch Cases: Each case maps directly to your original functions:
    • numeric: Generates 5 unique integers from 1 to 20 (matches your vmn() function)
    • character: Generates 5 unique lowercase letters (matches your vma() function)
    • logical: Replicates your vector.maker.bool() logic exactly—combines integers 1-20 (which convert to TRUE when cast to logical) with the result of 1:10 == TRUE (which gives one TRUE and nine FALSEs), then samples 5 unique values and converts them to logical.

Example Usage

Try these commands to test the function:

  • Numeric vector: vector_generator("numeric")
  • Character vector: vector_generator("character")
  • Logical vector: vector_generator("logical")
  • Default (numeric): vector_generator()

内容的提问来源于stack exchange,提问作者Patricia Timoner McManus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:50:19