如何在 R 数据框中替换完整列?
若要替换 R 数据框中的完整列,我们可以使用 delta 运算符将原始列设置为新值。例如,如果我们有一个名为 df 的数据框,其中包含一列 x,其中 500 个值来自正态分布,那么要将其替换为均值为 25 的正态分布,可以执行 df$x<−rnorm(500,5)。
示例 1
考虑以下数据框 −
x1<−rpois(20,2) x2<−rpois(20,2) x3<−rpois(20,3) df1<−data.frame(x1,x2,x3) df1
输出
x1 x2 x3 1 1 3 1 2 0 3 1 3 1 4 3 4 4 3 2 5 0 4 1 6 2 3 6 7 2 2 4 8 4 1 2 9 0 4 5 10 1 1 4 11 3 3 1 12 1 3 3 13 1 1 10 14 2 1 3 15 2 3 3 16 1 1 3 17 2 4 8 18 1 3 2 19 1 3 0 20 1 1 0
将 x3 替换为 lambda 2 的泊松分布 −
示例
df1$x3<−rpois(20,2) df1
输出
x1 x2 x3 1 1 3 1 2 0 3 2 3 1 4 0 4 4 3 1 5 0 4 3 6 2 3 2 7 2 2 2 8 4 1 3 9 0 4 2 10 1 1 3 11 3 3 1 12 1 3 2 13 1 1 3 14 2 1 0 15 2 3 0 16 1 1 1 17 2 4 2 18 1 3 3 19 1 3 4 20 1 1 1
示例 2
y1<−rnorm(20,1,0.05) y2<−rnorm(20,1,0.75) y3<−rnorm(20,1,0.05) y4<−rnorm(20,1,0.05) df2<−data.frame(y1,y2,y3,y4) df2
输出
y1 y2 y3 y4 1 1.0141018 0.71738148 0.9420311 1.0009205 2 1.0258060 1.03202326 1.0183309 1.0953612 3 0.9743657 1.58046651 1.0517233 1.0596325 4 1.0199483 1.08089945 0.9873335 0.9910522 5 1.0740019 2.13191506 1.0805077 1.0352464 6 1.0504327 1.55207108 1.0105741 0.9503119 7 0.9656107 1.51496959 1.0856465 1.0721738 8 1.0314142 −0.62997358 0.9007254 0.9555474 9 0.9688579 2.05252761 0.9920891 0.9693772 10 0.9811555 1.58630688 0.9550110 0.9611265 11 0.9594506 1.49768858 0.9792084 0.9442541 12 0.9891804 0.50237995 0.8821927 1.0816134 13 1.0939416 0.16319086 1.0682660 0.9552987 14 1.0437989 2.06159460 1.0034599 0.9708994 15 0.9660916 1.21363074 0.9780202 0.9961647 16 1.0634504 0.82467522 1.0184935 1.0586482 17 0.9907623 1.06935013 1.0507246 0.9516461 18 1.0336085 2.07268738 0.9972536 0.9815386 19 1.0366192 2.20583375 1.0393763 0.9332535 20 1.0861114 0.02966648 1.0502028 0.9452250
将 y2 替换为均值为 1、标准差为 0.05 的正态分布 −
示例
df2$y2<−rnorm(20,1,0.05) df2
输出
y1 y2 y3 y4 1 1.0141018 0.9238429 0.9420311 1.0009205 2 1.0258060 0.9940841 1.0183309 1.0953612 3 0.9743657 0.9705115 1.0517233 1.0596325 4 1.0199483 0.9521452 0.9873335 0.9910522 5 1.0740019 0.9531263 1.0805077 1.0352464 6 1.0504327 1.0587658 1.0105741 0.9503119 7 0.9656107 0.9558315 1.0856465 1.0721738 8 1.0314142 1.0368435 0.9007254 0.9555474 9 0.9688579 0.9117594 0.9920891 0.9693772 10 0.9811555 1.0072615 0.9550110 0.9611265 11 0.9594506 0.9935137 0.9792084 0.9442541 12 0.9891804 1.0018355 0.8821927 1.0816134 13 1.0939416 0.9531882 1.0682660 0.9552987 14 1.0437989 0.8805634 1.0034599 0.9708994 15 0.9660916 1.0378592 0.9780202 0.9961647 16 1.0634504 1.0431174 1.0184935 1.0586482 17 0.9907623 1.0666330 1.0507246 0.9516461 18 1.0336085 0.9449561 0.9972536 0.9815386 19 1.0366192 0.9172270 1.0393763 0.9332535 20 1.0861114 0.9739211 1.0502028 0.9452250
广告