subset rows randomly in R by criteria

Viewed 89

I'm trying to subset a dataframe into a smaller one based on one of the column values, the data frame as the following head()

Experiment SRA_Sample              Sample_Name Grupo_analisis body_site
1  SRX567480  SRS626942 GTEX-111CU-0226-SM-5GZXC              1   Thyroid
2  SRX615964  SRS644174 GTEX-111FC-1026-SM-5GZX1              1   Thyroid
3  SRX563960  SRS625636 GTEX-111VG-0526-SM-5N9BW              3   Thyroid
4  SRX564185  SRS625665 GTEX-111YS-0726-SM-5GZY8              1   Thyroid
5  SRX559141  SRS624025 GTEX-1122O-0226-SM-5N9DA              1   Thyroid
6  SRX561718  SRS625313 GTEX-1128S-0126-SM-5H12S              1   Thyroid
         molecular_data_type    sex Group ShortName
1 Allele-Specific Expression   male   NIT 111CU_NIT
2              RNA Seq (NGS)   male   NIT 111FC_NIT
3              RNA Seq (NGS)   male   ELI 111VG_ELI
4 Allele-Specific Expression   male   NIT 111YS_NIT
5              RNA Seq (NGS) female   NIT 1122O_NIT
6 Allele-Specific Expression female   NIT 1128S_NIT

There are 3 groups ELI, NIT y SCI, I want to randomly select 10 samples of each class. I'm trying:

> set.seed(12)
> targets10<- filter(targets, targets$Group== ("NIT", "ELI", "SFI")) %>% sample_n(., 10)

or

>targets10<-filter(targets, targets$Group== "NIT","ELI","SFI") %>% sample_n(., 10)

is giving me the following error: Error in (~targets$Group == "NIT") & ~"ELI" : operations are possible only for numeric, logical or complex types

Could someone help me???

than you so much in advance

1 Answers

Try reformatting your code like this:

dplyr solution:

targets10 <- targets %>% 
  filter(Group %in% c("NIT", "ELI", "SFI")) %>% 
  sample_n(., 10)

base R solution:

targets10 <- subset(survey, Group %in% c("NIT", "ELI", "SFI"))
targets10 <- sample_n(targets10, 10)

edit:

To take 10 samples from each group, you just need to add group_by:

targets10 <- targets %>% 
  filter(Group %in% c("NIT", "ELI", "SFI")) %>% 
  group_by(Group) %>% 
  sample_n(., 10)
Related