Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

How to slice data from a middle index until the end without using `length` in R (like you can in python)?

In python, I can slice the last four items from a five-item list (pull values from it) like so: mylist[1:] (note, 0-based indexing). In R, it seems that not having something after the colon is an error. In both languages, I can put the last argument as the length of the list, but that's not always convenient (e.g. inline slicing: colnames(iris)[2:length(colnames(iris))]).

Is there any such syntax in R?

question from:https://stackoverflow.com/questions/15127457/how-to-slice-data-from-a-middle-index-until-the-end-without-using-length-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well this is confusing coming from a python background, but mylist[-1] seems to do the trick. The negative in this case can be read as "except," i.e. take everything except column 1. So colnames(iris)[-1] works to grab all but the first item.

Oh, and to exclude more items, treat it as a range that is excluded, so colnames(iris)[-2:-4] would keep only the first and all items after (and including) the fifth one.

For others coming from python, check out this nice slideshow comparing R to python.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...