[R] HELP: How to subtract a vector out of each row of a matrix or array
Nordlund, Dan (DSHS/RDA)
NordlDJ at dshs.wa.gov
Thu Nov 15 20:31:53 CET 2007
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Geoffrey Zhu
> Sent: Thursday, November 15, 2007 10:45 AM
> To: r-help at r-project.org
> Subject: [R] HELP: How to subtract a vector out of each row
> of a matrix or array
>
> 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)
>
Geoffrey,
How about
x <- apply(y,1,'-',m)
Hope this is helpful,
Dan
Daniel J. Nordlund
Research and Data Analysis
Washington State Department of Social and Health Services
Olympia, WA 98504-5204
More information about the R-help
mailing list