你可以使用下面的基本语法,用dplyr包中的函数在R语言中替换一个数据框中的多个值。
library(dplyr)
df %>%
mutate(var1 = recode(var1, 'oldvalue1' = 'newvalue1', 'oldvalue2' = 'newvalue2'),
var2 = recode(var2, 'oldvalue1' = 'newvalue1', 'oldvalue2' = 'newvalue2'))
下面的例子展示了如何在实践中使用这种语法:
例子:使用dplyr替换多个值
假设我们在R语言中拥有以下数据框,其中包含各种篮球运动员的信息:
#create data frame
df <- data.frame(conf=c('East', 'East', 'West', 'West', 'North'),
position=c('Guard', 'Guard', 'Guard', 'Guard', 'Forward'),
points=c(22, 25, 29, 13, 18))
#view data frame
df
conf position points
1 East Guard 22
2 East Guard 25
3 West Guard 29
4 West Guard 13
5 North Forward 18
现在假设我们想替换数据框中的以下数值:
- 'conf'列
- 用'E'替换'East'
- 用'W'替换'West'
- 用'N'代替'North'
- 'position'列
- 用'G'代替'Guard'
- 用'F'替换'Forward'
我们可以使用**mutate()和recode()**函数来做到这一点:
library(dplyr)
#replace multiple values in conf and position columns
df %>%
mutate(conf = recode(conf, 'East' = 'E', 'West' = 'W', 'North' = 'N'),
position = recode(position, 'Guard' = 'G', 'Forward' = 'F'))
conf position points
1 E G 22
2 E G 25
3 W G 29
4 W G 13
5 N F 18
注意,'conf'和'position'列中的每个值都被替换成了特定的值。
同时注意到 "点 "列中的值保持不变。
其他资源
下面的教程解释了如何使用dplyr执行其他常见任务。