将一列中的多个值替换为一个 [英] replace multiple values in a column for a single one

查看:119
本文介绍了将一列中的多个值替换为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很基本的问题。我在一个列中有几个要替换的值,例如:

I have a rather basic question. I have several values in a column that I would like to replace for a single one, for instance:

a< -data.frame(T = LETTERS [5:20],V = rnorm(16,10,1))

,我想更改所有 T中的,, S, T代表 AB,所以我尝试了

and I would like to change all "E", "S", "T" in T for "AB", so I tried

a[a$T==c("E","S","T")]<-"AB"

它给了我几个警告,最后全部替换为 AB。

and it gives me several warnings, and ends up replacing all to "AB"

我认为这与关卡和关卡的标签有关,但是我无法替换只有一些值,我将不得不重新标记每个值。抱歉,给您带来麻烦,谢谢您!

I think it has something to do with levels and level's labels but I was not able to replace only some of the values, I would have to re-label each. Sorry for the trouble, and thanks for any help!

推荐答案

您可以使用函数 recode()从库 car 更改因子的值。

You can use function recode() from library car to change values also for the factors.

library(car)
a$T<-recode(a$T,"c('E','S','T')='AB'")

如果您需要用其他不同的值替换不同的值,则可以在一个函数调用中编写所有语句。

If you need to replace different values with different other values then all statements can be written in one function call.

recode(a$T,"c('E','S','T')='AB';c('F','G','H')='CD'")

这篇关于将一列中的多个值替换为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆