# How to create a new column in an R data frame based on some condition of another column?

Sometimes we want to change a column or create a new by using other columns of a data frame in R, this is mostly required when we want to create a categorical column but it can be done for numerical columns as well. For example, we might want to create a column based on salary for which if salaries are greater than the salary in another column then adding those salaries otherwise taking the difference between them. This will help us to understand whether the salaries in two columns are equivalent, lesser, or greater. In R, we can use transform function for this purpose.

## Example1

Consider the below data frame:

Live Demo

> set.seed(1001)
> x1<-rpois(20,1)
> y1<-rpois(20,5)
> df1<-data.frame(x1,y1)
> df1

## Output

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

Creating a column z1 in which y1 will be subtracted from x1 if x1 is greater than y1, otherwise added:

## Example

> df1<-transform(df1,z1=ifelse(x1>y1,x1-y1,x1+y1))
> df1

## Output

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

## Example2

> df2<-transform(df1,z1=ifelse(x1 df2

## Output

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

## Example3

> df3<-transform(df1,z1=ifelse(x1==y1,x1*y1,x1/y1))
> df3

## Output

  x1 y1 z1
1 4 6 0.6666667
2 1 4 0.2500000
3 1 9 0.1111111
4 1 6 0.1666667
5 1 4 0.2500000
6 2 7 0.2857143
7 0 6 0.0000000
8 0 3 0.0000000
9 0 8 0.0000000
10 2 4 0.5000000
11 1 5 0.2000000
12 0 9 0.0000000
13 2 10 0.2000000
14 1 4 0.2500000
15 0 3 0.0000000
16 2 2 4.0000000
17 0 2 0.0000000
18 0 6 0.0000000
19 0 6 0.0000000
20 2 2 4.0000000

Updated on: 06-Nov-2020

2K+ Views

##### Kickstart Your Career

Get certified by completing the course