student
student

Reputation: 187

How do I return multiple rows from multiple specific index ranges?

I have a dataset of 50 rows and I'm trying to get the data in rows 5-10, 12 and 21-23. Is there any way to do this in a single line?

Upvotes: 2

Views: 730

Answers (3)

U13-Forward
U13-Forward

Reputation: 71580

Or in base R you could use rbind:

rbind(df[5:10,], df[12,], df[21:23,])

Upvotes: 2

Vinícius Félix
Vinícius Félix

Reputation: 8811

A tidyverse approach

library(dplyr)

index_range <- c(5:10, 12, 21:23)

df %>% 
  slice(index_range)

Upvotes: 1

akrun
akrun

Reputation: 887301

Yes, just concatenate into a vector and use it as row index - for those sequence in range, use :

df1[c(5:10, 12, 21:23),]

Upvotes: 4

Related Questions