Kryptonien
Kryptonien

Reputation: 23

How to select rows with a special condition in R

I'm a beginner in R and my question is : in a matrix, I generated random mark between 0 and 20. Each row corresponds to a student, and each column to a subject. I would calculate how much students have the average in each subject, but I don't know how to test if the mark in each column is greater than 10. I think, I have to use "apply" and one function, but I don't succeed ...

nb.etu <- 60
nb.mat <- 12
notes <- matrix(
data = runif (n = nb.mat*nb.etu, min = 0, max = 20),
  nrow = nb.etu,
  ncol = nb.mat)

sexe <- sample(c("F","M"),size=60,replace=TRUE)
matrice <- cbind(notes,sexe)

# Class average

moy.mat <- apply(notes,2,mean)

# Student average

moy.etu <- apply(notes,1,mean)

# Student average for each subject

mod.info <- notes[,1:5]
moy.info <- apply(mod.info,1,mean)

mod.bio <- notes[,6:12]
moy.bio <- apply(mod.bio,1,mean)

Upvotes: 2

Views: 92

Answers (1)

dixhom
dixhom

Reputation: 3035

I assume you'd like to evaluate if the average of each column is more than 10 or not.

Try this one.

test.passed <- ifelse(moy.mat > 10, "Passed", "Failed")
rbind(notes, test.passed)

modified 1

Then try this one.

sum(apply(notes, 1, function(x) all(x > 10)))

What this does is...

  1. calculate if a student passed the test for each student
  2. take the sum of the students passed

Upvotes: 1

Related Questions