简体   繁体   中英

generating a vector that contains larger than and less than values

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.

You're returning the boolean vector, instead of the actual values

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.

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.

As @sconfluentus mentions what you need to do is:

 between_median_mean1 <- sample[sample>=median(sample) & mean(sample)<= sample]

ie 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.

We can use between

library(dplyr)
tibble(col1 = rexp(100, rate = 1.5) %>%
             filter(between(col1, median(sample), mean(sample)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM