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

R selecting rows and columns

I’m new to R and I have 2 questions. So I have a dataframe that looks like this table:

nr c0 c1 c2 c3
1 A B M Z
2 Z U C M
3 N K N D
4 M L Y E

First I would like to find all columns which contains the string M and store the column names in a new dataframe or a list:

c_names
c0
c2
c3

second I would like to select all rows containing the string M:

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

nr c0 c1 c2 c3
1 A B M Z
2 Z U C M
4 M L Y E

Thank you!

>Solution :

  • For your first question
> data.frame(c_names = names(df)[colSums(df == "M") > 0])
  c_names
1      c0
2      c2
3      c3
  • For your second question
> subset(df, rowSums(df == "M") > 0)
  nr c0 c1 c2 c3
1  1  A  B  M  Z
2  2  Z  U  C  M
4  4  M  L  Y  E
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