[R] overlaying the values of tab-delim file in to a pre-existing matrix

Gabor Grothendieck ggrothendieck at gmail.com
Sun Jul 30 18:22:28 CEST 2006


Please provide reproducible examples (as discussed at end of each
posting):

Lines <- "Apple  S 21.0
 Apple  A 21.6
 Apple  O 43.0
Orange  A 45.0
Orange  O 64.0
Orange  S 32.5
 Mango  M 40.3
 Mango  A 32.6
 Mango  S 24.6
"
tb <- read.table(textConnection(Lines))

# alternative 1 - create a matrix
tmat <- matrix(0, nrow = nlevels(tb$V2), ncol = nlevels(tb$V1),
	dimnames = list(levels(tb$V2), levels(tb$V1)))
tmat[cbind(tb$V2, tb$V1)] <- tb$V3

# alternative 2 - out is a data frame in wide format
out <- reshape(tb, dir = "wide", timevar = "V1", idvar = "V2")
# fix up rownames and colnames and remove first column
rownames(out) <- out[,1]
out <- out[,-1]
colnames(out) <- sub(".*[.]", "", colnames(out))
out[is.na(out)] <- 0



On 7/30/06, Srinivas Iyyer <srini_iyyer_bio at yahoo.com> wrote:
> Hello :
>
> I have matrix with dimensions(200 X 20,000). I
> have another
> file, a tab-delim file where first column
> variables are row
> names and second column variables are column
> names. Tab-delim file has smaller values than the
> matrix.
>
> Matrix = tmat
> tab-delim file read as data.frame = tb
>
>
>
> My aim is to read in a line in # Apple, S , 21.
> Find column Apple and row S and fill the value 21.
>
>
>
>
> For instance:
>
> > tmat
>     Apple Orange Mango Grape Star
> A     0      0     0     0    0
> O     0      0     0     0    0
> M     0      0     0     0    0
> G     0      0     0     0    0
> S     0      0     0     0    0
>
>
> > tb # tab- delim file read as a data.frame
>     V1  V2  V3
> 1  Apple  S  21
> 2  Apple  A  21.6
> 3  Apple  O  43
> 4 Orange  A  45
> 5 Orange  O  64
> 6 Orange  S  32.5
> 7  Mango  M  40.3
> 8  Mango  A  32.6
> 9  Mango  S  24.6
>
>
> Now I have to fill in the values in tb (V3) into tmat.
>
>
> For instance, (Apple, S) pair value is 21, I want
>
>
>     Apple Orange Mango Grape Star
> A     21.6   0     0     0    0
> O     0      0     0     0    0
> M     0      0     0     0    0
> G     0      0     0     0    0
> S     21     0     0     0    0
>
>
>
>
> > tbm <- as.matrix(tb)
> >
> tmat[cbind(match(tbm[,2],rownames(tmat)),match(tbm[,1],colnames(tmat)))]
> <-tbm[,3]
> Error: NAs are not allowed in subscripted assignments
>
>
> I am using R.2.2.1 on a
> Dell Latutite windows XP with 1GB RAM.
>
> Could any one please help me whats wrong with above
> code.
>
> thank you.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list