你可以使用以下方法,用dplyr包中的函数替换数据框中特定列的一个字符串。
方法1:用新字符串替换一个字符串
library(dplyr)
library(stringr)
df %>%
mutate(across('column_name', str_replace, 'old_value', 'new_value'))
方法2:用新字符串替换多个字符串
library(dplyr)
library(stringr)
df %>%
mutate(across('column_name', str_replace, 'old_value1|old_value2', 'new_value'))
下面的例子展示了如何在R语言中使用以下数据框架的每种方法:
#create data frame
df <- data.frame(conf=c('East', 'East', 'West', 'West'),
position=c('P_Guard', 'P_Guard', 'S_Guard', 'S_Guard'),
points=c(22, 25, 29, 13))
#view data frame
df
conf position points
1 East P_Guard 22
2 East P_Guard 25
3 West S_Guard 29
4 West S_Guard 13
例1:用新字符串替换一个字符串
下面的代码显示了如何将conf列中的'East'字符串替换为'Eastern'字符串:
library(dplyr)
library(stringr)
#replace 'East' with 'Eastern' in conf column
df %>%
mutate(across('conf', str_replace, 'East', 'Eastern'))
conf position points
1 Eastern P_Guard 22
2 Eastern P_Guard 25
3 West S_Guard 29
4 West S_Guard 13
请注意,conf列中的每个'East'字符串都被替换为'Eastern',而其他所有列都保持不变。
例2:用新字符串替换多个字符串
下面的代码显示了如何用一个空字符串替换conf列中的字符串'P_'和'S_':
library(dplyr)
library(stringr)
#replace 'P_' and 'S_' with empty string in position column
df %>%
mutate(across('position', str_replace, 'P_|S_', ''))
conf position points
1 East Guard 22
2 East Guard 25
3 West Guard 29
4 West Guard 13
注意,每个'P_'和'S_'字符串在position 列中都被替换成了一个空字符串,而其他所有列都保持不变。
请注意,我们使用了 "OR"(|)操作符来告诉R,我们想用一个空字符串来替换任何与'P_'或'S_'相同的字符串。
你可以随意使用多个 "OR"(|)运算符,以便在一列中一次性替换任意多的值。
其他资源
下面的教程解释了如何使用dplyr执行其他常见任务。