Difference between mean(c(1,2,21)) and mean(1,2,21) - r

What's the difference between these two?
mean(c(1,2,21))
and
mean(1,2,21)
The answers are different, but what's the meaning of each one?

mean(c(1,2,21))
#[1] 8
This passes a vector of three elements to the mean function and the mean value of these three elements is calculated.
mean(1,2,21)
#[1] 1
This passes 1 as the first argument, 2 as the second argument and 21 as the third argument to the mean function. mean passes these arguments to mean.default. In help("mean.default") you can find the arguments of this function:
The object you want the mean for.
the fraction (0 to 0.5) of observations to be trimmed from each end of x before the mean is computed. Values of trim outside that range are taken as the nearest endpoint.
a logical value indicating whether NA values should be stripped before the computation proceeds. (Since you pass a numeric value, it is coerced to logical automatically).
So you calculate this:
mean.default(1, 0.5, TRUE)
[1] 1

When using mean(c(1,2,21)) R is taking the mean out of the vector consisting of 1,2 and 21, in the second case, when using mean(1,2,21), is equivalent to mean(1, trim=2, na.rm=21) and R is taking the mean out one single number, 1, and you are passing value 2 to trim which controls for the fraction (0 to 0.5) of observations to be trimmed from each end of the vector before the mean is computed, and also you are giving value 21 to na.rm argument, which should be TRUE or FALSE, as you can see 2 and 21 without c are completely useless here.

Related

regarding the usage of runif function

I once saw the following R code,
x<-runif(3,max=c(10,20,30))
If the min is not set, what's the lower range for the generated random variable. Besides,when max is setup this way, my understanding is that it will iterate over the three values given in c() for each generated variable, is that right?
If you look at the ?runif help page, you'll see the default for min= is 0.
If you specify multiple values for max, the values are recycled so it's like the first value comes from unif(0,10), the second from unif(0,20) and the third from (0,30) and that pattern repeats for as many values as you request. If you only request one value
runif(1, max=c(10,20,30)
that would be the same as
runfi(1, max=10)
This is noted in the help page under the Value section
The numerical arguments other than n are recycled to the length of the result.
Per the documentation for this function (https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/Uniform), min takes on the value 0 unless explicitly passed.
And yes, that is correct - the function will iterate over the values given in c() for each value. If there isn't a value passed (e.g. you're generating 3 random variables and set c=(1,2)), then max will take the default value of 1 for the elements that don't have a set max value. An example showing how it iterates over c():
x<-runif(3,max=c(1,20, 7000000))
x
[1] 0.622216 7.463306 809194.417205

R - I don't understand why my code generates a count rather than a sum

I have a list of 10,000 values that look like this
Points
1 118
2 564
3 15
4 729
5 49
6 614
Calling the list t1 and running sum(t1>quantile(t(t1),0.8)) I would expect to get a sum of the values in the list that are greater than the 80th quantile, but what I really get is a count (not a sum) of all the values.
Try this:
sum(t1[t1>quantile(t(t1),0.8), ])
To see the difference check t1>quantile(t(t1),0.8) and then t1[t1>quantile(t(t1),0.8), ].
One is a logical vector and contains TRUE (resp. 1) if the value is greater than the 80% quantile and zero otherwise.
The other is t1 evaluate at that logical vector, so only values which are greater than the 80% quantile are returned
t1>quantile(t(t1),0.8) is a boolean, i.e. a sequence of TRUE/FALSE values (you can check it easily). Consequently, the sum of this vector is the number of occurrences of TRUE values, i.e. the count of individuals that satisfy the condition you specify.
Here is an example:
set.seed(123)
df <- data.frame(Point = rnorm(10000))
sum(df$Point > quantile(df$Point, 0.8))
The second line returns the sum for a boolean vector (TRUE/FALSE), hence you get the count (the number of times TRUE occurs). Use
sum(df$Point[df$Point > quantile(df$Point, 0.8)])
to get what you want.
You could use the ifelse fonction, that will add t1 if t1 is above your threshold and 0 otherwise
sum(ifelse(t1>quantile(t(t1),0.8),t1,0))

get location of row with median value in R data frame

I am a bit stuck with this basic problem, but I cannot find a solution.
I have two data frames (dummies below):
x<- data.frame("Col1"=c(1,2,3,4), "Col2"=c(3,3,6,3))
y<- data.frame("ColA"=c(0,0,9,4), "ColB"=c(5,3,20,3))
I need to use the location of the median value of one column in df x to then retrieve a value from df y. For this, I am trying to get the row number of the median value in e.g. x$Col1 to then retrieve the value using something like y[,"ColB"][row.number]
is there an elegant way/function for doing this? Solutions might need to account for two cases - when the sample has an even number of values, and ehwn this is uneven (when numbers are even, the median value might be one that is not found in the sample as a result of calculating the mean of the two values in the middle)
The problem is a little underspecified.
What should happen when the median isn't in the data?
What should happen if the median appears in the data multiple times?
Here's a solution which takes the (absolute) difference between each value and the median, then returns the index of the first row for which that difference vector achieves its minimum.
with(x, which.min(abs(Col1 - median(Col1))))
# [1] 2
The quantile function with type = 1 (i.e. no averaging) may also be of interest, depending on your desired behavior. It returns the lower of the two "sides" of the median, while the which.min method above can depend on the ordering of your data.
quantile(x$Col1, .5, type = 1)
# 50%
# 2
An option using quantile is
with(x, which(Col1 == quantile(Col1, .5, type = 1)))
# [1] 2
This could possibly return multiple row-numbers.
Edit:
If you want it to only return the first match, you could modify it as shown below
with(x, which.min(Col1 != quantile(Col1, .5, type = 1)))
Here, something like y$ColB[which(x$Col1 == round(median(x$Col1)))] would do the trick.
The problem is x has an even number of rows, so the median 2.5 is not an integer. In this case you have to choose between 2 or 3.
Note: The above works for your example, not for general cases (e.g. c(-2L,2L) or with rational numbers). For the more general case see #IceCreamToucan's solution.

Calculate mean value of two objects

Let's say we have two objects at the beginning:
a <- c(2,4,6)
b <- 8
If we apply the mean() function in each of them we get this:
> mean(a)
[1] 4
> mean(b)
[1] 8
... which is absolutely normal.
If I create a new object merging a and b...
c <- c(2,4,6,8)
and calculate its mean...
> mean(c)
[1] 5
... we get 5, which is the expected value.
However, I would like to calculate the mean value of both objects at the same time. I tried this way:
> mean(a,b)
[1] 4
As we can see, its value differs from the expected correct value (5). What am I missing?
As mentioned, the correct solution is to concatenate the vectors before passing them to mean:
mean(c(a, b))
The reason that your original code gives a wrong result is due to what mean’s second argument is:
## Default S3 method:
mean(x, trim = 0, na.rm = FALSE, ...)
So when calling mean with two numeric arguments, the second one is passed as the trim argument, which, in turn, controls how much trimming is to be done. In your case, 8 causes the function to simply return the median (meaningful values for trim would be fractions between 0 and 0.5).
If you print the argument a,b that you are feeding into the mean function, you will see that only a prints:
print(a,b)
[1] 2 4 6
So mean(a,b) only provides the mean of a.
mean(c(a,b)) will produce the expected answer of 5.

What does rnorm in R return when the sd argument contains a vector?

What does the following code do:
rnorm(10, mean=2, sd=1:10)
The first number is from N(2,1)
The second number if from N(2,2)
The third number is from N(2,3)
etc...?
The first argument tells R how many random variates you want returned. In this case, it will give you back 10 values. Those values will be drawn from normal distributions with mean equal to 2. In addition, all 10 values will be drawn from distributions with different standard deviations, the first with SD=1, the second 2, ..., the 10th SD=10. Perhaps the thing to understand is that R, by its nature, is vectorized. That is, there is no such thing as a scalar, only a vector of length=1. (I recognize that that doesn't make a lot of sense within pure math, but it does in computer science.) As a result, arguments are often 'recycled' so that they will all match the length of the longest vector, i.e., you end up with a vector of 10 means, each equal to 2, to match your vector of 10 SDs. HTH.

Resources