📜  在 R 编程中从字符向量中提取子字符串 – substring()函数

📅  最后修改于: 2022-05-13 01:55:24.883000             🧑  作者: Mango

在 R 编程中从字符向量中提取子字符串 – substring()函数

R 编程语言中的substring()函数用于提取字符向量中的子字符串。您可以轻松地从给定的字符串中提取所需的子字符串或字符。

R – substring()函数示例

示例 1:在 R 编程语言中使用子字符串函数提取值

R
# R program to illustrate
# substring function
 
# Calling substring() function
substring("Geeks", 2, 3)
substring("Geeks", 1, 4)
substring("GFG", 1, 1)
substring("gfg", 3, 3)


R
# R program to illustrate
# substring function
 
# Initializing a string vector
x < - c("GFG", "gfg", "Geeks")
 
# Calling substring() function
substring(x, 2, 3)
substring(x, 1, 3)
substring(x, 2, 2)


R
# R program to illustrate
# substring function
 
# Initializing a string vector
x <- c("GFG", "gfg", "Geeks")
 
# Calling substring() function
substring(x, 2, 3) <- c("@")
print(x)


输出 :

[1] "ee"
[1] "Geek"
[1] "G"
[1] "g"

示例 2:用 R 编程语言的字符串函数中的子字符串提取值

R

# R program to illustrate
# substring function
 
# Initializing a string vector
x < - c("GFG", "gfg", "Geeks")
 
# Calling substring() function
substring(x, 2, 3)
substring(x, 1, 3)
substring(x, 2, 2)

输出:

[1] "FG" "fg" "ee"
[1] "GFG" "gfg" "Gee"
[1] "F" "f" "e"

示例 3:在 R 中使用 substring()函数替换字符串

R

# R program to illustrate
# substring function
 
# Initializing a string vector
x <- c("GFG", "gfg", "Geeks")
 
# Calling substring() function
substring(x, 2, 3) <- c("@")
print(x)

输出:

[1] "G@G"   "g@g"   "G@eks"