Reputation: 47
I'm currently working on a question that is as follows:
Given that sample <- rexp(100, rate = 1.5)
, the median of the sample is generally smaller than the mean.
Generate a vector, between_median_mean
, that contains all values of sample that are larger than (or equal to) the median of sample , and less than (or equal to) the mean of sample.
my answer is: between_median_mean <- c((sample>=median(sample)&mean(sample)<=sample))
However, I'm only getting true/false, instead of generating values as the question asks. I would appreciate if any one can give some pointers on what I have done wrong/missing!
Edit: the output I'm getting is: [1] TRUE FALSE TRUE TRUE TRUE
for example.
Upvotes: 1
Views: 1376
Reputation: 886948
We can use between
library(dplyr)
tibble(col1 = rexp(100, rate = 1.5) %>%
filter(between(col1, median(sample), mean(sample)))
Upvotes: 0
Reputation: 81
As @sconfluentus mentions what you need to do is:
between_median_mean1 <- sample[sample>=median(sample) & mean(sample)<= sample]
i.e. to get the relevant slice of vector you need to slice the vector via new_vector = vector[condition]. You wrote the condition which states whether it is true or not and you just need to now apply TRUE/FALSE to whether the subset should include the value or not.
Upvotes: 1
Reputation: 547
Here is one solution:
(between_median_mean <- sample[sample >= median(sample) & sample <= mean(sample)])
The square brackets '[]' are used for subsetting. You say, show me only the values of sample that satisfy the conditions described.
Upvotes: 1
Reputation: 3632
If you want to return the actual values, you need to use the boolean vector to filter the initial sample. This is one of the many ways you can accomplish this task:
sample <- rexp(100, rate = 1.5)
test_condition_res <- sample >= median(sample) & mean(sample) <= sample
#Filter sample vector to return only TRUE values from the previous condition
between_median_mean <- sample[test_condition_res]
Hope this helps.
Upvotes: 2