简体   繁体   English

替换R中的列元素

[英]Replacing elements of a column in R

Lets say I have 2 vectors: 可以说我有2个向量:

a = c("1", "2", "3")

b = c("a", "b", "c")

and a data frame with a column that is equal to c("1", "1", "2", "1", "3", "2") . 以及具有等于c("1", "1", "2", "1", "3", "2")的列的数据帧。

What I want to do is to replace everything in the column that is equal to the items in vector a with the items in vector b (everything in the column that is equal to a[1] will turn into b[1]). 我想做的是用向量b中的项目替换等于向量a中的项目的列中的所有内容(等于a [1]的列中的所有内容都将变成b [1])。

As in I want my new column to be c("a", "a", "b", "a", "c", "b") . 如我希望我的新列是c("a", "a", "b", "a", "c", "b")

I know I have to use some sort of loop but everything that I have tried does not work. 我知道我必须使用某种循环,但是我尝试过的所有方法都不起作用。

Thanks for any replies! 感谢您的任何答复!

You can use match to do that. 您可以使用match来做到这一点。

c <- c("1", "1", "2", "1", "3", "2")
match(c, a)
#[1] 1 1 2 1 3 2
b[match(c, a)]
#[1] "a" "a" "b" "a" "c" "b"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM