How to assign a column value in a data frame based on another column in another R data frame?


To assign a column value based on another column, we can use ifelse function. The ifelse function checks whether the value in one column of one data frame matches the value in another column of another data frame by using equal sign (==) and then replace the original value with the new column if there is no match else returns the original value. Check out the below example to understand how it can be done.

Example

Consider the below data frame −

Live Demo

> x1<-rpois(20,2)
> x2<-rpois(20,5)
> df1<-data.frame(x1,x2)
> df1

Output

  x1 x2
1  3  5
2  3  7
3  0  6
4  0  5
5  4  6
6  3  8
7  1  5
8  0  8
9  4  6
10 1  2
11 2  3
12 2  6
13 0  0
14 1  9
15 0  0
16 4  2
17 3  5
18 3  8
19 1  3
20 2  7

Example

Live Demo

> y1<-rpois(20,2)
> y2<-rpois(20,5)
> df2<-data.frame(y1,y2)
> df2

Output

  y1  y2
1  3  8
2  4  11
3  3  8
4  2  2
5  1  3
6  1  4
7  1  7
8  1  2
9  5  2
10 2  4
11 2  3
12 1  3
13 1  5
14 3  4
15 0  3
16 2  5
17 3  5
18 1  7
19 5  10
20 2  6

Replacing values in x1 of df1, if x2 of df1 is same as y2 of df2 otherwise returning x1 in df1 −

> df1$x1<-ifelse(df1$x2==df2$y2,df2$y2,df1$x1)
> df1

Output

   x1 x2
1  3  5
2  3  7
3  0  6
4  0  5
5  4  6
6  3  8
7  1  5
8  0  8
9  4  6
10 1  2
11 3  3
12 2  6
13 0  0
14 1  9
15 0  0
16 4  2
17 5  5
18 3  8
19 1  3
20 2  7

Updated on: 04-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements