Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding value from one data.frame to another data.frame by matching a variable

Tags:

dataframe

r

Suppose I have two data frames df1 and df2 as follows

Df1

Id Price Profit Month
10  5     2      1
10  5     3      2
10  5     2      3
11  7     3      1
11  7     1      2
12  0     0      1
12  5     1      2

Df2

Id Name
9  Kane
10 Jack
10 Jack
11 Will
12 Matt
13 Lee
14 Han

Now I want to insert a new column in Df1 named Name and get its value from Df2 based on matching Id

So modified Df1 will be

Id Price Profit Month Name
10  5     2      1    Jack
10  5     3      2    Jack
10  5     2      3    Jack
11  7     3      1    Will
11  7     1      2    Will
12  0     0      1    Matt
12  5     1      2    Matt
like image 715
Jay khan Avatar asked Mar 27 '16 07:03

Jay khan


2 Answers

df1 <- data.frame(Id=c(10L,10L,10L,11L,11L,12L,12L),Price=c(5L,5L,5L,7L,7L,0L,5L),Profit=c(2L,3L,2L,3L,1L,0L,1L),Month=c(1L,2L,3L,1L,2L,1L,2L),stringsAsFactors=F);
df2 <- data.frame(Id=c(9L,10L,10L,11L,12L,13L,14L),Name=c('Kane','Jack','Jack','Will','Matt','Lee','Han'),stringsAsFactors=F);
df1$Name <- df2$Name[match(df1$Id,df2$Id)];
df1;
##   Id Price Profit Month Name
## 1 10     5      2     1 Jack
## 2 10     5      3     2 Jack
## 3 10     5      2     3 Jack
## 4 11     7      3     1 Will
## 5 11     7      1     2 Will
## 6 12     0      0     1 Matt
## 7 12     5      1     2 Matt
like image 149
bgoldst Avatar answered Oct 05 '22 02:10

bgoldst


use left_join in dplyr

library(dplyr)
left_join(df1, df2, "Id")

eg:

> left_join(df1, df2)
Joining by: "Id"
  Id Price Profit Month Name
1 10     5      2     1 Jack
2 10     5      3     2 Jack
3 10     5      2     3 Jack
4 11     7      3     1 Will
5 11     7      1     2 Will
6 12     0      0     1 Matt
7 12     5      1     2 Matt

Data wrangling cheatsheet by RStudio is a very helpful resource.

like image 34
Vincent Bonhomme Avatar answered Oct 05 '22 02:10

Vincent Bonhomme