Spencer
Spencer

Reputation: 67

Print range of ROWS in R

I'm trying to print a range of rows in a large dataset but everything comes back with an error mentioning columns. I've tried a variation of punctuation but struggling to find anything that dictates the actual syntax for print rows and not columns. Can someone assist?

INDIANA.LONG <- INDIANA %>% 
  pivot_longer(X2010:X2019, names_to = "YEARS", values_to = "COUNT") %>%
  print[75:83,]

This is the error:

Error in `vectbl_as_col_location()`:
! Can't subset columns past the end.
ℹ Locations 75, 76, 77, 78, 79, … don't
  exist.
ℹ There are only 6 columns.

Upvotes: 0

Views: 579

Answers (4)

Spencer
Spencer

Reputation: 67

I solved the question - had to rewrite the pivot_longer function. Thanks everyone!

INDIANA.LONG <-  pivot_longer(data= INDIANA, cols= (X2010:X2019), names_to = "YEARS", values_to = "COUNT")

INDIANA.LONG[75:83,]

Upvotes: 0

AndrewGB
AndrewGB

Reputation: 16856

Another option is to use the base R notation inside the pipe prior to using print:

library(dplyr)

INDIANA.LONG <- INDIANA %>%
  pivot_longer(X2010:X2019, names_to = "YEARS", values_to = "COUNT") %>%
  .[75:83, ] %>%
  print

Upvotes: 0

njp
njp

Reputation: 698

Try using slice from dplyr before the print statement:

INDIANA.LONG <- INDIANA %>% 
  pivot_longer(X2010:X2019, names_to = "YEARS", values_to = "COUNT") %>%
  slice(75:83) %>%
  print

Upvotes: 1

langtang
langtang

Reputation: 24722

within a dplyr/tidyr pipeline, you can use between(), row_number(), and filter()

filter(between(row_number(), 75,83))

instead of your print() call.

Upvotes: 0

Related Questions