如何仅将 R 数据框中的一列与数字相乘?
要仅将一列与数字相乘,我们可以简单地使用乘法运算符 *,但需要用新值替换原始列。例如,如果我们有一个名为 df 的数据框,它包含三列 x1、x2 和 x3,并且我们想将第二列 x2 乘以 2,那么它可以作为 df$x2<−df$x2*2 完成。
示例 1
考虑以下数据框 -
set.seed(212)输出结果x1<−rpois(20,2)
x2<−rpois(20,5)
x3<−rpois(20,2)
df1<−data.frame(x1,x2,x3)
df1
x1 x2 x31 1 5 3
2 3 5 1
3 3 6 4
4 1 0 2
5 0 3 1
6 0 7 4
7 4 10 4
8 4 8 3
9 1 7 0
10 2 2 0
11 2 1 1
12 2 7 1
13 3 2 1
14 1 3 3
15 1 3 2
16 3 5 2
17 3 2 1
18 1 4 1
19 2 5 2
20 4 6 2
通过将其中的值乘以 2 来替换列 x2 -
df1$x2<−df1$x2*2输出结果df1
x1 x2 x31 1 10 3
2 3 10 1
3 3 12 4
4 1 0 2
5 0 6 1
6 0 14 4
7 4 20 4
8 4 16 3
9 1 14 0
10 2 4 0
11 2 2 1
12 2 14 1
13 3 4 1
14 1 6 3
15 1 6 2
16 3 10 2
17 3 4 1
18 1 8 1
19 2 10 2
20 4 12 2
例2
y1<−rnorm(20)输出结果y2<−rnorm(20)
y3<−rnorm(20)
y4<−rnorm(20)
df2<−data.frame(y1,y2,y3,y4)
df2
y1 y2 y3 y41 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
通过将其中的值乘以 *1 来替换列 y1 -
df2$y1<−df2$y1*(−1)输出结果df2
y1 y2 y3 y41 −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
以上是 如何仅将 R 数据框中的一列与数字相乘? 的全部内容, 来源链接: utcz.com/z/343873.html