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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With