如何将三个已创建的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 yourvmn()function)character: Generates 5 unique lowercase letters (matches yourvma()function)logical: Replicates yourvector.maker.bool()logic exactly—combines integers 1-20 (which convert toTRUEwhen cast to logical) with the result of1:10 == TRUE(which gives oneTRUEand nineFALSEs), 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
相关产品推荐
相关产品推荐

