Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Avoiding for loops with automatic iteration

Tags:

r

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 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?

like image 759
SFun28 Avatar asked Apr 28 '11 22:04

SFun28


1 Answers

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"
like image 92
IRTFM Avatar answered Nov 15 '22 05:11

IRTFM