Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to multiply only one column in an R data frame with a number?
To multiply only one column with a number, we can simply use the multiplication operator * but need to replace the original column with the new values. For example, if we have a data frame called df that contains three columns x1, x2, and x3, and we want to multiply the second column x2 with 2 then it can be done as df$x2<−df$x2*2.
Example1
y1<−rnorm(20) y2<−rnorm(20) y3<−rnorm(20) y4<−rnorm(20) df2<−data.frame(y1,y2,y3,y4) df2
Output
y1 y2 y3 y4 1 0.17051839 −1.07371818 0.717652086 −0.6692174 2 0.26654381 −0.82881794 1.144774784 1.0708255 3 1.17587680 −0.03197159 −0.257318856 −0.2734330 4 0.79978274 1.14677652 −1.052941918 0.8212265 5 0.36352605 0.95455643 0.002662389 0.8991729 6 −0.52918622 −1.19824723 1.121770768 −0.1345990 7 −1.30278723 0.90339625 −1.637918585 −0.3986243 8 −2.01380274 −0.61700004 1.319289169 1.4223520 9 −0.10499300 −0.99640769 1.508072921 −0.8711021 10 −0.57019817 0.23396114 0.371342290 −0.5071846 11 −0.92964644 −2.82593133 −0.191162636 0.2482026 12 −0.62824719 1.39458991 −0.250602510 −0.5094344 13 −1.16899182 0.48402510 0.849597620 0.5386604 14 −0.12800221 −1.01570468 −1.370769300 0.3641254 15 1.60649960 1.00993852 −0.181644717 0.7057080 16 −0.09581029 −0.40099838 0.392519844 −1.6369244 17 −0.43375271 −0.29316467 −0.233208374 0.1270293 18 −0.96182839 0.54334525 1.550101688 2.0853380 19 −1.50775746 −0.89573880 0.366389303 0.3372866 20 1.90255916 −1.41836692 0.428073142 −0.1576013
Replacing the column y1 by multiplying the values in it with *1 −
df2$y1<−df2$y1*(−1) df2
Output
y1 y2 y3 y4 1 −0.17051839 −1.07371818 0.717652086 −0.6692174 2 −0.26654381 −0.82881794 1.144774784 1.0708255 3 −1.17587680 −0.03197159 −0.257318856 −0.2734330 4 −0.79978274 1.14677652 −1.052941918 0.8212265 5 −0.36352605 0.95455643 0.002662389 0.8991729 6 0.52918622 −1.19824723 1.121770768 −0.1345990 7 1.30278723 0.90339625 −1.637918585 −0.3986243 8 2.01380274 −0.61700004 1.319289169 1.4223520 9 0.10499300 −0.99640769 1.508072921 −0.8711021 10 0.57019817 0.23396114 0.371342290 −0.5071846 11 0.92964644 −2.82593133 −0.191162636 0.2482026 12 0.62824719 1.39458991 −0.250602510 −0.5094344 13 1.16899182 0.48402510 0.849597620 0.5386604 14 0.12800221 −1.01570468 −1.370769300 0.3641254 15 −1.60649960 1.00993852 −0.181644717 0.7057080 16 0.09581029 −0.40099838 0.392519844 −1.6369244 17 0.43375271 −0.29316467 −0.233208374 0.1270293 18 0.96182839 0.54334525 1.550101688 2.0853380 19 1.50775746 −0.89573880 0.366389303 0.3372866 20 −1.90255916 −1.41836692 0.428073142 −0.1576013
Advertisements
