Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Bulk column value replacement [duplicate]

Tags:

r

In R I have a data.frame and I'd like to do a bulk update.

My table looks like

Col1  Col2  Col3
A      123   456
A      789   012
B      345   678
B      789   012

I want to scan over the table and replace A with "Apple" and B with "Banana"

In my case, the list of replacements is quite long (~30 items) so I have them both in lists like:

old<-c('A','B')
new<-c('Apple','Banana')
like image 644
Exie Avatar asked Apr 22 '26 20:04

Exie


1 Answers

I like working with named vectors:

   df <- data.frame(Col1=c('A','A','B','B'), 
                    Col2=c(123,789,345,789), 
                    Col3=c(456,012,678,012))
oldv <- c('A','B')
newv <- c('Apple','Banana')
names(newv) <- oldv
df$Col1 <- newv[ df$Col1 ]

yields

  > df
    Col1 Col2 Col3
1  Apple  123  456
2  Apple  789   12
3 Banana  345  678
4 Banana  789   12
like image 140
Mike Wise Avatar answered Apr 24 '26 08:04

Mike Wise



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!