[R] Merging different columns in one matrix

arun smartpink111 at yahoo.com
Fri Dec 6 16:36:14 CET 2013


Hi,
May be this helps:

dat1 <- read.table(text="
a     a     b     b     c     c
x     y     x     y     x     y
12   34   256  25    5   32
5    45    23   452   21   45",sep="",header=TRUE,stringsAsFactors=FALSE,check.names=FALSE) 


 mat1 <- matrix(0,5,5,dimnames=list(NULL,c("x",letters[1:4])))
 mat1[,1]<- sort(unique(as.numeric(unlist(dat1[-1,which(dat1=="x",arr.ind=TRUE)[,2]]))))

dat1New <- dat1[-1,which(dat1=="x",arr.ind=TRUE)[,2]]
dat2New <- dat1[-1,which(dat1=="y",arr.ind=TRUE)[,2]]
mat1[,2:4] <-sapply(seq_len(ncol(dat1New)),function(i) {x1 <-dat2New[match(mat1[,1],dat1New[,i]),i]
x1[is.na(x1)] <-0
as.numeric(x1)})
 mat1
#       x  a   b  c d
#[1,]   5 45   0 32 0
#[2,]  12 34   0  0 0
#[3,]  21  0   0 45 0
#[4,]  23  0 452  0 0
#[5,] 256  0  25  0 0


A.K.


Hello everyone, 

I have a dataframe made as follows: 

a     a     b     b     c     c 
x     y     x     y     x     y 
12   34   256  25    5   32 
5    45    23   452   21   45 
...   ...    ...   ...    ...    ... 

My intention is to create just one matrix made as follows 

x     a     b     c     d 
5     45   0     32    0 
12   34   0     0      0 
21   0     0     45    0 
23   0    452   0     0 
256  ...  ...     ...   ... 
... 

As you can see I want on the first column all the values 
collected from all the x columns and ordered. On the other columns I 
want the y-values related to every letter (a-b-c...). For example the 
first value on the x column is 5 (the smallest). It is present in the a 
x-values (first matrix) so in the second table I report its related 
y-value (45). However 5 is not present in the b x-values so I report a 0
 on the second table. And so on. 

I don't know if it's a difficult task but I had several problems
 with the double header handling and the data. I looked for some clues 
on the internet but documentation is very fragmented and lacking. 

(So, in addition, any recommendation for good R books?)



More information about the R-help mailing list