0

I am beginning with R. I am testing with a dataset called "students". Its a matrix with the name of the student and their classification (A, B, C) on several subjects (Vars). I would like to filter the name and list the subject(s) when the subject has a value "B" or "C". Please see what I have and what I would like to get.

Thank you for your help

What I have...

Name    MATH    LANG    GYMN    LIT SOC
Nigel   A   B   C   A   C
John    C   C   A   B   C
Martha  A   A   A   A   A

I wish...

Nigel   
LANG 
GYMN
SOC

John
MATH
LANG
LIT
SOC
Hector Haffenden
  • 1,360
  • 10
  • 25
Nigel
  • 3
  • 4
  • 2
    Hi, and welcome to SO! In general it's hard to answer questions that provide screenshots of data, because we don't know how the data is actually organised in your R session. Take a look at [how to make a reproducible example in R](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). In this case, we don't know if your Student Matrix is actually a matrix or a dataframe, and we don't know whether you want a list, character vector or a dataframe out. – Calum You Apr 24 '19 at 22:17

1 Answers1

0

Using the following data,

data <- data.frame(row.names = c("Nigel", "John", "Martha"),
               MATH = c("A", "C", "A"),
               LANG = c("B", "C", "A"),
               GYMN = c("C", "A", "A"),
               LIT = c("A", "B", "A"),
               SOC = c("C", "C", "A"))

We can apply our test to each row of the data, (there are more efficient ways, but this is very instructive),

rst <- apply(data, 1, function(x) which(x == "B" | x == "C"))

$Nigel
LANG GYMN  SOC 
   2    3    5 

$John
MATH LANG  LIT  SOC 
   1    2    4    5 

$Martha
named integer(0)

This returns a list with the relevant subjects, use, for example rst$Nigel to get the relevant students information

Hector Haffenden
  • 1,360
  • 10
  • 25