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:
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