Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I subset a dataframe based on ID letters?

I have this df

df = data.frame(x = c('1E','2E','1F','2F'), y =1:4 )

and I wish to subset it into 2 dataframes based on the letters E and F

the resulted dataframes are as follows

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   x y
1 1E 1
2 2E 2
   x y
1 1F 3
2 2F 4

>Solution :

You can use split with gsub. In the second argument, you can use whatever function that will make it so that you extract the letters of df$x:

split(df, gsub("\\d", "", df$x))

Use list2env if you want to subsequently convert the list into separate dataframes in your environment.

list2env(split(df, gsub("\\d", "", df$x)), .GlobalEnv)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading