Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Create a new column in a data frame using a mapping from another data frame

Tags:

r

I have the following data frames.

> temp
  x1    x2
1  1 INDIA
2  2 INDIA
3  3    US
4  4    US

> PortfolioIndices
  Country   Index CCY
1   INDIA   CNX50 INR
2      US   SP500 USD
3      UK FTSE100 GBP

I want to add one more column to temp with currencies corresponding to the respective countries in x2 column using the mapping from PortfolioIndices data frame. Something like this should be the output

> temp
  x1    x2  x3
1  1 INDIA INR
2  2 INDIA INR
3  3    US USD
4  4    US USD

I don't want to use for loop as the actual data could be very large and using a for loop in that case would be very inefficient. Is there a better way to achieve the given output?

Thanks in advance.

like image 603
user3212376 Avatar asked Jan 19 '14 15:01

user3212376


1 Answers

You can use merge:

> merge(temp, PortfolioIndices, by.x = "x2", by.y = "Country")
     x2 x1 Index CCY
1 INDIA  1 CNX50 INR
2 INDIA  2 CNX50 INR
3    US  3 SP500 USD
4    US  4 SP500 USD
like image 166
Sven Hohenstein Avatar answered Nov 03 '22 08:11

Sven Hohenstein