Did you know you can use "["
and "[["
as function names for subsetting with calls to the apply
-type functions?
For example, suppose you have a bunch of identifier strings like "ZYY-43S-CWA3"
and you want to pull off the bit before the first hyphen ("ZYY"
in this case). (For code to create random IDs like that, see the end of this post.)
Suppose the IDs are in a vector of character strings, id
.
If I wanted to grab the bit before the first hyphen, I would typically use strsplit
and then sapply
with function(a) a[1]
, as so:
sapply(strsplit(id, "-"), function(a) a[1])
But in place of function(a) a[1]
, you can use "[", 1
, as follows:
sapply(strsplit(id, "-"), "[", 1)
I think that’s kind of cute. You can use "[["
the same way, if you’re working with lists.
Here’s some code to create random IDs of this form, to test out the above:
nind <- 8 lengths <- c(3, 3, 4) id <- NULL for(i in seq(along=lengths)) { randchar <- sample(c(LETTERS, 0:9), nind*lengths[i], replace=TRUE) randstring <- apply(matrix(randchar, ncol=lengths[i]), 1, paste, collapse="") if(is.null(id)) id <- randstring else id <- paste(id, randstring, sep="-") }
21 Aug 2013 at 1:03 am
Another useful trick is:
sapply(strsplit(id, "-"), head, n = 1)
Of course, that is to extract only the first element. Similarly, the last element can be extracted via
tail
.21 Aug 2013 at 10:47 am
Good one. I guess I should have gone after the middle bit in my example, so that
head
andtail
wouldn’t apply.sapply(strsplit(id, "-"), "[", 2)
21 Aug 2013 at 9:25 am
Reblogged this on m's R Blog and commented:
[ and [[ are a little bit faster (~15%) in the case below:
21 Aug 2013 at 10:06 am
unlist(strsplit(id, "-"))[1]
21 Aug 2013 at 10:49 am
I was thinking of
id
as a vector. If it hadn just one element, I’d do just what you suggest.