R - Avoiding for loops with automatic iteration -
this contrived example i'm using understand r better. lets want subset character vector called "test". want return each element value third character last character. doesn't work:
test = c( "jane" , "jerry" , "joan" ) substr( test , 3 , length( test ) ) expecting: "ne" , "rry" , "an"
is there way without loop?
use nchar()
. it's vectorized:
> test = c( "jane" , "jerry" , "joan" ) > substr( test , 3 , nchar( test ) ) [1] "ne" "rry" "an"
given nchar return vector of lengths, , substr likewise vectorized, , expects work vector arguments, 1 potential puzzle why accepts scalar argument of 3
. answer here scalars start , stop arguments recycled match length of input character vector. could, therefore, use 1:2 start argument , alternating complete , complete strings:
> substr( test , 1:2 , nchar( test ) ) [1] "jane" "erry" "joan"
Comments
Post a Comment