how to make a sub vector from another vector that includes all values that are true in R programming

Viewed 26

Im quite new to programming and am facing a certain issue. I have the below 2 vectors one has expenses and the other has revenues for 12 months: '''

revenue <- c(14574.49, 7606.46, 8611.41, 9175.41, 8058.65, 8105.44, 11496.28, 9766.09, 10305.32, 14379.96, 10713.97, 15433.50)
expenses <- c(12051.82, 5695.07, 12319.20, 12089.72, 8658.57, 840.20, 3285.73, 5821.12, 6976.93, 16618.61, 10054.37, 3803.96)

'''

I have to be able to pull a list of the profit(revenue - expenses) where the revenues are greater than the mean revenue of the 12 months. I cant seem to figure it out.

This is what I used below to try to get this: '''

for(i in 1:length(revenue)){
  if(revenue > mean.revenue){
  good_months <- c(revenue>mean.revenue)
  }
  }
good_months

'''

Problem with this is that it only pulls out either true or false for those months. How can I get only the True values?

1 Answers

Perhaps you can use this

> which(revenue > mean(revenue))
[1]  1  7 10 11 12

> (revenue - expenses)[revenue > mean(revenue)]
[1]  2522.67  8210.55 -2238.65   659.60 11629.54
Related