[R] help about R basic

David Winsemius dwinsemius at comcast.net
Sun Sep 25 15:40:47 CEST 2011


On Sep 25, 2011, at 5:03 AM, 阮铮 wrote:

> This is my first time to ask for help in the R mailing list, so  
> sorry for my misbehavior.
>
>
> The question is actually an example of the apply function embedded  
> in R. Code is here:
>
>> x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
>> > dimnames(x)[[1]] <- letters[1:8]
>> > x   x1 x2 a  3  4 b  3  3 c  3  2 d  3  1 e  3  2 f  3  3 g  3  4  
>> h  3  5
>> > cave <- function(x, c1, c2) c(mean(x[c1]), mean(x[c2]))
>> > apply(x,1, cave,  c1="x1", c2=c("x1","x2"))
>>        a b   c d   e f   g h
>> [1,] 3.0 3 3.0 3 3.0 3 3.0 3
>> [2,] 3.5 3 2.5 2 2.5 3 3.5 4

>> > x["x1"]
>> [1] NA

But that's the wrong way to access columns

 > x[,"x1"]
a b c d e f g h
3 3 3 3 3 3 3 3

 > x[, c("x1","x2")]
   x1 x2
a  3  4
b  3  3
c  3  2
d  3  1
e  3  2
f  3  3
g  3  4
h  3  5

(I do not know why Sarah Goslee is telling you that you cannot access  
matrices with column names. You clearly can do so. Maybe I misread her  
statement.)


>> > mean(x["x1"])
>> [1] NA
>> > mean(x[c("x1", "x2")])
>> [1] NA

> What confused me is how do apply work to deal with x[c1] and x[c2]  
> (the output seems unchanged) ? Why can't I call them out the apply  
> function ?

What do you mean by that sentence? The apply function is sending rows  
of the matrix and since only one row is being sent the dimensions are  
reduced and the argument to your function is a vector rather than a  
matrix.

-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list