character - R: substr() results differently in for loop and vector -


i'm using substr cut off last 3 letters string list: postal_code0

postal_code0 >[1] "n14be"   "n14be"   "n14be"   "n14be"   "n14be"   "n16dd"   "n16dd"   "n16dd"   "n16dd"   "n16dd"   >[11] "n11tw"   "n11tw"   "n11tw"   "n11tw"   "n11tw"   "n5"      "n160lu"  "n2"      "n200au"  "n200au"  >[21] "london"  "n15"     "n5"      ""      > outcode <- substr(postal_code0, 1, nchar(postal_code0)-3) > outcode [1] "n1"   "n1"   "n1"   "n1"   "n1"   "n1"   "n1"   "n1"   "n1"   "n1"   "n1"   "n1"   "n1"   "n1"   "n1"   [16] ""     "n16"  ""     "n20"  "n20"  "lon"  ""     ""     ""        

it removes elements completely, i'd keep, if use loop same function, returns outcome i'd like.

> outcode0 <- c() > (i in 1: length(postal_code0)){ + outcode0[i] <- substr(postal_code0[i], 1, nchar(postal_code0)-3) + }  > outcode0 [1] "n1" "n1" "n1" "n1" "n1" "n1" "n1" "n1" "n1" "n1" "n1" "n1" "n1" "n1" "n1" "n5" "n1" "n2" "n2" "n2" "lo" [22] "n1" "n5" ""  

what's difference between 2 functions? , how

outcode0 

without using loop?

according last comment left, following should do:

len <- nchar(postal_code0) substring(postal_code0, 1, ifelse(len <= 3, len, len - 3)) 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -