求助:实现含for循环的R语言字符串统计命名列表函数
Implementing R Function
f3 with a For Loop Got it! Since you already have a solid vectorized version of f3, let's walk through converting it to use a for loop—this is a great way to build intuition for how iteration works in R.
Step-by-Step Breakdown
First, we need to:
- Initialize counters for digits, lowercase letters, and uppercase letters starting at 0.
- Split the input string into individual characters so we can loop through each one.
- For each character, check which category it falls into and increment the corresponding counter.
- Return the final counts as a named list matching your required structure.
The For Loop Implementation
f3 <- function(s) { # Start all counters at 0 num_count <- 0 lower_count <- 0 upper_count <- 0 # Split the string into a vector of single characters all_chars <- strsplit(s, "")[[1]] # Iterate over each character in the vector for (char in all_chars) { # Check if the character is a digit [0-9] if (grepl("[0-9]", char)) { num_count <- num_count + 1 } # Check if it's a lowercase letter [a-z] else if (grepl("[a-z]", char)) { lower_count <- lower_count + 1 } # Check if it's an uppercase letter [A-Z] else if (grepl("[A-Z]", char)) { upper_count <- upper_count + 1 } # Non-alphanumeric characters are ignored, just like your original function } # Return the named list with numeric values return(list( num = as.numeric(num_count), l = as.numeric(lower_count), L = as.numeric(upper_count) )) }
Verify the Output
When you run:
str(f3("123abA"))
You'll get exactly the output you specified:
List of 3 $ num: num 3 $ l : num 2 $ L : num 1
Key Notes
- We use
strsplit(s, "")[[1]]becausestrsplitreturns a list—adding[[1]]extracts the character vector we need for the loop. greplworks here just like it does instr_count, checking if the character matches the regex pattern.- Converting counters to
numericensures consistency with your original function (even though integers would work too, this keeps the output identical).
内容的提问来源于stack exchange,提问作者Eva Sørensen
相关产品推荐
相关产品推荐

