简体   繁体   中英

Replacing elements of a column in R

Lets say I have 2 vectors:

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") .

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]).

As in I want my new column to be 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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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