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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With