我正在使用substr来截断字符串列表中的最后三个字母: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" "" "" ""
它完全删除了一些我想保留的元素,但是如果我使用for循环来获得相同的函数,它会返回我想要的结果。
> outcode0 <- c()
> for (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" ""
这两个功能有什么区别?以及如何获得
outcode0
不使用for循环?
答案 0 :(得分:2)
根据您最后的评论,以下内容应该如下:
len <- nchar(postal_code0)
substring(postal_code0, 1, ifelse(len <= 3, len, len - 3))