# How to change data.table object columns value to maximum in R?

Sometimes we need to compare the maximum values or set some column of a data frame or data.table object to their maximums, especially in research studies that may require biasedness. Therefore, we can set all the column values to maximum. In case of a data.table object, we can use single square bracket to access and assign the column values to their maximum as shown in the below examples.

## Example

> library(data.table)
> x1<-rpois(20,5)
> x2<-rpois(20,5)
> DT1<-data.table(x1,x2)
> DT1

## Output

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

Setting all values to maximum in both the columns of DT1 −

## Example

> DT1[,":="(x1=max(x1),x2=max(x2))]
> DT1

## Output

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

## Example

> y1<-rnorm(20)
> y2<-rnorm(20)
> DT2<-data.table(y1,y2)
> DT2

## Output

y1 y2
1: 0.023625687 1.4483042
2: 1.106287710 1.0704318
3: 1.467489995 -0.1895449
4: 0.547832725 -0.5910900
5: -0.733764184 0.1977163
6: 2.021397912 0.4160044
7: -0.001008175 -0.6264825
8: 0.237018174 -0.4992914
9: -0.842971527 -0.7227745
10: -1.444723647 -0.1965069
11: -2.415372720 0.2633523
12: 1.317615263 0.5652904
13: -0.858622646 1.1681279
14: -0.585999557 -0.5307442
15: 0.330628856 -0.7169733
16: 0.177377373 0.1853514
17: -0.061377177 -0.3185333
18: -0.180351581 -1.2435872
19: -1.040703567 1.6828731
20: 1.367891650 -0.3071294

Setting all values to maximum in both the columns of DT2 −

## Example

> DT2[,":="(y1=max(y1),y2=max(y2))]
> DT2

## Output

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