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

在R语言中解析字符串:编写接收字符串并返回“Thanks.”的函数

Hey there! Let's break down what you need in R—both string parsing basics and that custom function you want. I'll walk you through it clearly:

R语言字符串解析与自定义函数实现

一、常见字符串解析操作

R has great tools for string manipulation, whether you use base R functions or the popular stringr package (part of the tidyverse). Here are some common tasks:

1. 分割字符串

Split a string into a list of substrings using a delimiter:

# Base R approach
text <- "apple,banana,orange,grape"
split_result <- strsplit(text, ",")[[1]]  # [[1]] to extract the vector from the list
print(split_result)
# Output: [1] "apple"  "banana" "orange" "grape"

# Tidyverse stringr approach (more readable)
library(stringr)
str_split(text, ",")[[1]]

2. 提取子字符串

Grab specific characters from a string by position:

text <- "Hello Stack Overflow"
# Base R: substr(input, start_position, end_position)
substr(text, 7, 11)  # Extracts "Stack"
# stringr equivalent: str_sub(input, start, end)
str_sub(text, 7, 11)

3. 正则表达式匹配提取

Pull out patterns (like phone numbers, emails) using regex:

text <- "Contact me at 555-123-4567 or support@example.com"
# Base R: Use gregexpr + regmatches
phone_num <- regmatches(text, gregexpr("\\d{3}-\\d{3}-\\d{4}", text))[[1]]
print(phone_num)
# Output: [1] "555-123-4567"

# stringr: str_extract_all for all matches
str_extract_all(text, "\\w+@\\w+\\.\\w+")[[1]]  # Extract email
# Output: [1] "support@example.com"

二、自定义函数:输入字符串输出"Thanks."

Creating this function is straightforward. We'll even add a quick check to ensure the input is a string, making the function more robust:

# Define the custom function
thank_you <- function(input_string) {
  # Optional: Validate input type
  if (!is.character(input_string)) {
    stop("Oops! Input must be a string.")
  }
  # Return the required output
  return("Thanks.")
}

# Test the function
test_input <- "This is my input string"
result <- thank_you(test_input)
print(result)
# Output: [1] "Thanks."

If you skip the input check, the function still works—adding it just helps catch accidental non-string inputs (like numbers) and gives a clear error message.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:18:46