Home > Enterprise >  Choose rows from dataframe by index
Choose rows from dataframe by index

Time:08-22

I have a dataframe that looks like this:

Food  Car  Airplane  Slice  Team
A      F     A         F     A
#With 15 more rows

What I would like to do is to choose row number 1 and 14.

This code works to get the first row

data[rownames(data) == 1,]
Food  Car  Airplane  Slice  Team
A      F     A         F     A

How can I do so the code chooses two rows? data[rownames(data) == 1, 14,] doesn't work.

CodePudding user response:

tidyverse approach:

library(tidyverse)

df <- data.frame(a = rnorm(15), b = rnorm(15))

df %>% 
  slice(1,14)

CodePudding user response:

If you want choose rows by index

data[1,]

If you want choose rows by List of Index values

data[c(1,14),]

A full explanation can you find here: https://sparkbyexamples.com/r-programming/select-rows-by-index-in-r/

CodePudding user response:

Or using filter:

library(dplyr)

df %>% 
  filter(row_number() %in% c(1,14))
  •  Tags:  
  • r
  • Related