5

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
0

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

1 Comment

I tried these two packages. And they both give the results correctly. I liked the format of dplyr the best.
2

Give by a try:

do.call(rbind, by(X, X$Gender, head, 3))

1 Comment

this was the fastest way to get the result I needed without having to install packages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.