[R] HELP: How to subtract a vector out of each row of a matrix or array

Geoffrey Zhu zyzhu2000 at gmail.com
Thu Nov 15 19:45:25 CET 2007


Hi All,

I am having great trouble doing something pretty simple.

 Here is what I did:

> x <- read.table("clipboard")
> dim (x)
[1] 126 10
> typeof(x)
[1] "list"

> w <- array(x)
> typeof(w)
"list"

Q1: How come after constructing an array out of the list, the type of
the array is still "list"?


> w <- as.array(x)

Error in `dimnames<-.data.frame`(`*tmp*`, value = list(c("V1", "V2", "V3",  :
  invalid 'dimnames' given for data frame

Q2: How do I covnert a two dimensional list to an array then?

> y<-as.matrix(x)
> dim(y)
[1] 126 10

Finally, this works.

> m<-colMeans(y)
> m
         V1          V2          V3          V4          V5          V6
0.098965679 0.075252330 0.046776996 0.021706852 0.005319685 0.003453889
         V7          V8          V9         V10
0.037819506 0.021107303 0.039035427 0.002694224

Get the mean of each column.

Q3: Now the big question. I want to substract V1 from each element of
column 1, V2 from each element of column 2, ... How do I do this?

I ended up doing this, which is highly inefficient.

> z<- t(t(y)-m)

Thanks,
Geoffrey



More information about the R-help mailing list