如何在 R 中使用 str_replace?
str_replace()用于将给定的字符串替换为 R 编程语言中的特定值。它在 stringr 库中可用,所以我们必须加载这个库。
语法:
str_replace( "replacing string", "replaced string")
在哪里,
- 替换字符串是要替换的字符串
- 替换的字符串是最终的字符串
我们将在数据框中使用 str_replace。我们可以使用以下语法替换数据框列中的特定字符串
str_replace(dataframe$column_name, "replacing string", "replaced string")
在哪里,
- 数据框是输入数据框
- column_name 是数据框中的列
示例:
R
# load the library
library(stringr)
# create a dataframe with 3 columns
data = data.frame(name1=c('java', 'python', 'php'),
name2=c('html', 'css', 'jsp'),
marks=c(78, 89, 77))
# replace the java with oops in name1 column
print(str_replace(data$name1, "java", "oops"))
# replace the htmlwith oops in name2 column
print(str_replace(data$name2, "html", "HTML5"))
R
# load the library
library(stringr)
# create a dataframe with 3 columns
data = data.frame(name1=c('java', 'python', 'php'),
name2=c('html', 'css', 'jsp'),
marks=c(78, 89, 77))
# replace the java with nothing in name1 column
print(str_replace(data$name1, "java", ""))
# replace the html with nothing in name2 column
print(str_replace(data$name2, "html", ""))
R
# load the library
library(stringr)
# create a dataframe with 3 columns
data = data.frame(name1=c('java', 'python', 'php'),
name2=c('html', 'css', 'jsp'),
marks=c(78, 89, 77))
# replace the java with oops and php with sql in name1 column
print(str_replace_all(data$name1, c("java"="oops", "php"="sql")))
# replace the html with r and jsp with servletsin name2 column
print(str_replace_all(data$name2, c("html"="R", "jsp"="servlets")))
输出:
[1] "oops" "python" "php"
[1] "HTML5" "css" "jsp"
方法 2:用 Nothing 替换字符串
我们可以将字符串替换为“”为空。
语法:
str_replace(dataframe$column_name, "replacing string", "")
示例:
R
# load the library
library(stringr)
# create a dataframe with 3 columns
data = data.frame(name1=c('java', 'python', 'php'),
name2=c('html', 'css', 'jsp'),
marks=c(78, 89, 77))
# replace the java with nothing in name1 column
print(str_replace(data$name1, "java", ""))
# replace the html with nothing in name2 column
print(str_replace(data$name2, "html", ""))
输出:
[1] "" "python" "php"
[1] "" "css" "jsp"
方法 3:替换多个字符串
我们可以使用 str_replace_all 方法替换特定列中的多个字符串。
语法:
str_replace_all(dataframe$column_name, c(“string1” = “new string”,……………..,”stringn” = “new string”))
示例:
R
# load the library
library(stringr)
# create a dataframe with 3 columns
data = data.frame(name1=c('java', 'python', 'php'),
name2=c('html', 'css', 'jsp'),
marks=c(78, 89, 77))
# replace the java with oops and php with sql in name1 column
print(str_replace_all(data$name1, c("java"="oops", "php"="sql")))
# replace the html with r and jsp with servletsin name2 column
print(str_replace_all(data$name2, c("html"="R", "jsp"="servlets")))
输出:
[1] "oops" "python" "sql"
[1] "R" "css" "servlets"