What are idioms for taking a head or a tail of a vector, either up to an index, or from an index to the end? Also -- is it necessary to use length(v) to refer to the last element? E.g., Python has v[:3] # indices 0,1,2 v[3:] # indices 3,4,... v[-1] # the last element of v v[:-1] # all but last Cheers, Alexy
Alexy Khrabrov wrote:> What are idioms for taking a head or a tail of a vector, either up to > an index, or from an index to the end? Also -- is it necessary to > use length(v) to refer to the last element? E.g., Python has > > v[:3] # indices 0,1,2 > v[3:] # indices 3,4,... > v[-1] # the last element of v > v[:-1] # all but last?head For example:> x <- runif(10)> x[1] 0.60253459 0.51895186 0.01080359 0.68675829 [5] 0.58588120 0.41019752 0.25345482 0.84928989 [9] 0.78826981 0.01696331> head(x, 3)[1] 0.60253459 0.51895186 0.01080359> tail(x, -3)[1] 0.68675829 0.58588120 0.41019752 0.25345482 [5] 0.84928989 0.78826981 0.01696331> tail(x, 1)[1] 0.01696331> head(x, -1)[1] 0.60253459 0.51895186 0.01080359 0.68675829 [5] 0.58588120 0.41019752 0.25345482 0.84928989 [9] 0.78826981> Cheers, > Alexy > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.-- Chuck Cleland, Ph.D. NDRI, Inc. 71 West 23rd Street, 8th floor New York, NY 10010 tel: (212) 845-4495 (Tu, Th) tel: (732) 512-0171 (M, W, F) fax: (917) 438-0894
Please someone correct me if i'm wrong, but i think this is impossible with the current R language. ':' is an ordinary function (see get(":")) just like "[", so v[1:3] is actually the composition of two functions, it is the same as "["(":"(1,3)). The ":" has no idea about whether it'll be embedded into a "[" function of not, it certainly cannot know the length of the vector i'll be indexed with. While this has the drawback you mentioned, it also has some advantages, when someone writes something like lapply(l, "[[", 1) or lapply(10:1, ":", 20) So, I'm afraid you'll have to live with length(v). Gabor On Sat, Nov 24, 2007 at 12:49:59PM +0300, Alexy Khrabrov wrote:> What are idioms for taking a head or a tail of a vector, either up to > an index, or from an index to the end? Also -- is it necessary to > use length(v) to refer to the last element? E.g., Python has > > v[:3] # indices 0,1,2 > v[3:] # indices 3,4,... > v[-1] # the last element of v > v[:-1] # all but last > > Cheers, > Alexy > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.-- Csardi Gabor <csardi at rmki.kfki.hu> MTA RMKI, ELTE TTK