How to multiply each value in a column by a constant in R?


To multiply each value in a column by a constant, we can use multiplication sign *.

For example, if we have a data frame called df that contains a column say x. Now, if we want to multiply each value in x with 10 then we can use the below mentioned command −

df$x<-10*(df$x)

Example 1

Following snippet creates a sample data frame −

x<-rpois(20,1)
df1<-data.frame(x)
df1

Output

The following dataframe is created −

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

To multiply each value in x with 5, add the following code to the above snippet −

x<-rpois(20,1)
df1<-data.frame(x)
df1$x<-5*(df1$x)
df1

Output

If you execute all the above given snippets as a single program, it generates the following Output −

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

Example 2

Following snippet creates a sample data frame −

y<-round(rnorm(20),1)
df2<-data.frame(y)
df2

Output

The following dataframe is created −

     y
1   1.0
2  -1.8
3   0.0
4   0.2
5  -2.9
6   1.0
7  -0.6
8  -1.3
9  -0.2
10 -0.3
11  0.3
12  0.8
13 -0.9
14  0.4
15 -2.2
16  1.1
17  0.5
18  3.0
19  1.6
20  1.0

To multiply each value in y with 2, add the following code to the above snippet −

y<-round(rnorm(20),1)
df2<-data.frame(y)
df2$y<-2*(df2$y)
df2

Output

If you execute all the above given snippets as a single program, it generates the following Output −

     y
1   2.0
2  -3.6
3   0.0
4   0.4
5  -5.8
6   2.0
7  -1.2
8  -2.6
9  -0.4
10 -0.6
11  0.6
12  1.6
13 -1.8
14  0.8
15 -4.4
16  2.2
17  1.0
18  6.0
19  3.2
20  2.0

Updated on: 02-Nov-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements