Reputation: 659
I am struggling to understand why this happens:
a<-c(1.1,1.2,1.3)
b<-c(2.1,2.3,2.6)
c<-c(1.6,2.3,2.6)
mean<-rowMeans(matrix(c(a,b,c),ncol=3))
mean #### This are the mean values
[1] 1.600000 1.933333 2.166667
mean(a[1],b[1],c[1]) #### trying to calculate the mean of 1.1 ,2.1 and 1.6
[1] 1.1 #### Why is this not 1.6??
Upvotes: 1
Views: 1027
Reputation: 3
Mabye your problem is that your matrix is transposed? Try this:
mean<-rowMeans(matrix(c(a,b,c),ncol=3, byrow=T))
Upvotes: 0
Reputation: 94317
R's argument matching has caught you out:
> mean(9999,2,3,4,5)
[1] 9999
help(mean)
says:
Usage:
mean(x, ...)
and then says it computes the mean of x
and passes ...
to other methods. All the numbers after 9999 in my example get captured in the dot-dot-dot.
R then calls mean.default
because 9999 is just a number, and mean.default
doesn't do anything with the dot-dot-dot arguments, including erroring if there's anything in them.
You can use this to add arbitrary useless things to your function calls:
> mean(c(1,2,3,4), monkeys=TRUE)
[1] 2.5
Upvotes: 14
Reputation: 18612
Your call to mean
in mean(a[1],b[1],c[1])
is only operating on the first element, i.e. mean(a[1])
. You need to concatenate a[1],b[1],c[1]
like this:
> mean(c(a[1],b[1],c[1]))
[1] 1.6
Upvotes: 5