当用R中的[]引用时,取一个变量的观察值

时间:2014-03-02 14:53:13

标签: r

我的问题如下:

在数据帧x中,我有一个名为zipcode的变量,其值可以是5位数的4。我想要做的是在所有4位数的邮政编码之前添加0。

但是以下代码不起作用:

x$zipcode[nchar(zipcode == 4)] = paste("0", x$zipcode, sep="")

我还写了一个for循环来做到这一点,这有效,但需要很长时间才能运行。我想知道这项任务是否有快速解决方案。感谢

1 个答案:

答案 0 :(得分:3)

您只需要sprintf

sprintf('%05d',x$zipcode)

示例:

> set.seed(1)
> x <- data.frame(zipcode=sample(1000:99999, 100))
> x$zipcode
  [1] 27285 37839 57711 90909 20965 89936 94517 66414 63277  7116 21389 18477
 [13] 69007 39021 77203 50264 72032 99181 38616 77952 93517 21997 65501 13427
 [25] 27448 39215  2325 38846 87075 34684 48711 60338 49844 19429 82881 67154
 [37] 79601 11682 72619 41700 82240 65032 78477 55726 53418 79110  3308 48223
 [49] 73463 69546 48260 86215 44348 25221  7993 10841 32293 52315 66500 41252
 [61] 91319 30048 46419 33886 65394 26526 48344 76813  9334 87596 34544 84044
 [73] 35296 34019 48123 89260 86503 39578 77894 96025 43996 71481 40566 33182
 [85] 75888 21049 71339 13036 25281 15174 24701  6829 64527 87669 78039 79857
 [97] 46028 41558 81196 60828
> sprintf('%05d',x$zipcode)
  [1] "27285" "37839" "57711" "90909" "20965" "89936" "94517" "66414" "63277"
 [10] "07116" "21389" "18477" "69007" "39021" "77203" "50264" "72032" "99181"
 [19] "38616" "77952" "93517" "21997" "65501" "13427" "27448" "39215" "02325"
 [28] "38846" "87075" "34684" "48711" "60338" "49844" "19429" "82881" "67154"
 [37] "79601" "11682" "72619" "41700" "82240" "65032" "78477" "55726" "53418"
 [46] "79110" "03308" "48223" "73463" "69546" "48260" "86215" "44348" "25221"
 [55] "07993" "10841" "32293" "52315" "66500" "41252" "91319" "30048" "46419"
 [64] "33886" "65394" "26526" "48344" "76813" "09334" "87596" "34544" "84044"
 [73] "35296" "34019" "48123" "89260" "86503" "39578" "77894" "96025" "43996"
 [82] "71481" "40566" "33182" "75888" "21049" "71339" "13036" "25281" "15174"
 [91] "24701" "06829" "64527" "87669" "78039" "79857" "46028" "41558" "81196"
[100] "60828"