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

求助:实现含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:

  1. Initialize counters for digits, lowercase letters, and uppercase letters starting at 0.
  2. Split the input string into individual characters so we can loop through each one.
  3. For each character, check which category it falls into and increment the corresponding counter.
  4. 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]] because strsplit returns a list—adding [[1]] extracts the character vector we need for the loop.
  • grepl works here just like it does in str_count, checking if the character matches the regex pattern.
  • Converting counters to numeric ensures consistency with your original function (even though integers would work too, this keeps the output identical).

内容的提问来源于stack exchange,提问作者Eva Sørensen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 16:43:01