0

I have a dataset consisting of 250 observations. I want to select all observations expect last. I know I can do this by following codes. But if do not know exact number of observations how I can do this.

dataset(mtcars)
mtcars_lag<-mtcars[1:31,]
## skipping first observation and selecting all
mtcars_forward<-mtcars[2:32,]
sim235
  • 219
  • 1
  • 9
  • 1
    You just want to leave out the last row? You can do `head(mtcars, -1)` You can leave the first out with `tail(mtcars,-1)`. Is that what you are after? – MrFlick Jul 18 '20 at 00:41

1 Answers1

0

Using nrow() gets you the number of observations in the dataset. mtcars_subset <- mtcars[1:(nrow(mtcars)-1), ] will fetch you all observations except the last one.

EDIT: Added parenthesis in line with suggestion from MrFlick.

Elbee685
  • 3
  • 2
  • 1
    Actually that won't work due to operator precedence. You need to add some parenthesis like `mtcars[1:(nrow(mtcars)-1), ] ` – MrFlick Jul 18 '20 at 00:46
  • Elbee685, I suggest you either [edit] your answer and fix it or delete your question, as an inaccurate answer can be frustrating if new readers don't know that it doesn't work correctly (and comments are easily/often skipped). Thanks! – r2evans Jul 18 '20 at 02:30
  • Fair enough. Added the edit, r2evans. – Elbee685 Jul 18 '20 at 18:31