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


i have 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 r code produce new dataframe, y, takes subset of x gender , first 3 rows of each gender (1:3) give result follows.

>y height  weight gender 5       60      m 5       70      m 6       80      m 5       70      f 5       80      f 6       60      f 

try slice dplyr

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

or using data.table

library(data.table) setdt(x)[,.sd[1:3] , gender] 

Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -