1

I have following data frame in R

Amount   Transaction_Type
62.81          1
6.66           2
19.9           3
24.02          2
24.02          2
45.2           1
19.76          3  

The other dataframe I have is following

Transaction        Transaction_Type   
  CARD                    1
  CASH                    2
  VOUCHER                 3

I want to replace Transaction values in the first dataframe,so it will look like following

Amount      Transaction_Type
62.81          CARD
6.66           CASH
19.9           VOUCHER
24.02          CASH
24.02          CASH
45.2           CARD
19.76          VOUCHER

Please help.

1
  • Why not simply df1$Transaction_Type <- df2[match(df1$Transaction_Type, df2$Transaction_Type), 1] ? Commented Jul 30, 2016 at 12:39

3 Answers 3

2

This is easy to do using the merge method of R. In your example:

a=data.frame(
   "Amount"=c(62.81,6.66,19.9,24.02,24.02,45.2,19.76),
   "Transaction_Type"=c(1,2,3,2,2,1,3))
t=data.frame(
   "Transaction"=c("CARD","CASH","VOUCHER"),
   "Transaction_Type"=c(1,2,3))

if you run the following: merge(a,t,by="Transaction_Type") you will output the structure you want:

  Transaction_Type Amount Transaction
1                1  62.81        CARD
2                1  45.20        CARD
3                2   6.66        CASH
4                2  24.02        CASH
5                2  24.02        CASH
6                3  19.90     VOUCHER
7                3  19.76     VOUCHER

Of course afterwards, you can keep the columns you want.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

1

We can use match from base R

df1$Transaction_Type <- df2$Transaction[match(df1$Transaction_Type, 
                                df2$Transaction_Type)]
df1$Transaction_Type
#[1] "CARD"    "CASH"    "VOUCHER" "CASH"    "CASH"    "CARD"    "VOUCHER"

Or another base R option is

unname(with(df2, setNames(Transaction, Transaction_Type))[as.character(df1$Transaction_Type)])
#[1] "CARD"    "CASH"    "VOUCHER" "CASH"    "CASH"    "CARD"    "VOUCHER"

Comments

1

Assuming the first dataframe is df1, and the second is df2:

library(dplyr)

left_join(df1, df2, by = "Transaction_Type") %>% select(-Transaction_Type)

#  Amount Transaction
#1  62.81        CARD
#2   6.66        CASH
#3  19.90     VOUCHER
#4  24.02        CASH
#5  24.02        CASH
#6  45.20        CARD
#7  19.76     VOUCHER

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.