Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset n number of rows from a dataframe, based on a categorical variable, in R

Tags:

r

subset

rows

I have a dataframe (say x) in R:

> x
Height  Weight Gender
5     60    m
5     70    m
6     80    m
4     90    m
4     60    m
5     70    f
5     80    f
6     60    f
4     90    f
4     60    f

I need an R code that will produce a new dataframe, say y, that takes the subset of X by Gender and only the first three rows of each gender (1:3) to give the result as follows.

>y
Height  Weight Gender
5       60      m
5       70      m
6       80      m
5       70      f
5       80      f
6       60      f
like image 405
gg-14 Avatar asked Apr 22 '15 16:04

gg-14


People also ask

How do I subset certain rows in R?

By using bracket notation on R DataFrame (data.name) we can select rows by column value, by index, by name, by condition e.t.c. You can also use the R base function subset() to get the same results. Besides these, R also provides another function dplyr::filter() to get the rows from the DataFrame.

How do you subset a DataFrame in R based on column value?

How to subset the data frame (DataFrame) by column value and name in R? By using R base df[] notation, or subset() you can easily subset the R Data Frame (data. frame) by column value or by column name.

How do you select rows from a DataFrame based on column values in R?

Select Rows by list of Column Values. By using the same notation you can also use an operator %in% to select the DataFrame rows based on a list of values. The following example returns all rows when state values are present in vector values c('CA','AZ','PH') .

Which of the following functions returns a subset of the rows of a data frame based on a condition?

The filter() function is used to subset a data frame, retaining all rows that satisfy your conditions.


1 Answers

Try slice from dplyr

library(dplyr)
x %>%
    group_by(Gender) %>% 
    slice(1:3)

Or using data.table

library(data.table)
setDT(x)[,.SD[1:3] , Gender]
like image 189
akrun Avatar answered Nov 03 '22 16:11

akrun