开发者

R - Avoiding for loops with automatic iteration

This is a contrived example that I'm using to hopefully understand R better. Lets say I want to subset a character vector called "test". I want to return each element value from the third character to the last 开发者_Python百科character. This doesn't work:

test = c( "Jane" , "Jerry" , "Joan" )
substr( test , 3 , length( test ) )
expecting: "ne" , "rry" , "an"

Is there a way to do this without a for loop?


Use nchar(). It's vectorized:

> test = c( "Jane" , "Jerry" , "Joan" )
> substr( test , 3 , nchar( test ) )
[1] "ne"  "rry" "an" 

Given that nchar will return a vector of lengths, and that substr is likewise vectorized, and so expects to work with vector arguments, the one potential puzzle is why it even accepts a scalar argument of 3. The answer here is that scalars to the start and stop arguments get recycled to match the length of the input character vector. You could, therefore, even use 1:2 for the start argument and get alternating complete and almost complete strings:

>      substr( test , 1:2 , nchar( test ) )
[1] "Jane" "erry" "Joan"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜