Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subsetting one matrix based in another matrix

Tags:

r

subset

I would like to select the R based on G strings to obtain separated outputs with equal dimensions. This are my inputs:

R <- 'pr_id  sample1  sample2 sample3
            AX-1   100       120     130    
            AX-2   150       180     160
            AX-3   160       120     196'
R <- read.table(text=R, header=T)

G <- 'pr_id  sample1  sample2 sample3
            AX-1   AB       AA     AA    
            AX-2   BB       AB     NA
            AX-3   BB       AB     AA'
G <- read.table(text=G, header=T)

This are my expected outputs:

AA <- 'pr_id  sample1  sample2 sample3
            AX-1   NA       120     130    
            AX-2   NA       NA     NA
            AX-3   NA       NA     196'
AA <- read.table(text=AA, header=T)

AB <- 'pr_id  sample1  sample2 sample3
            AX-1   100       NA     NA    
            AX-2   NA       180     NA
            AX-3   NA       120     NA'
AB <- read.table(text=AB, header=T)

BB <- 'pr_id  sample1  sample2 sample3
            AX-1   NA       NA     NA    
            AX-2   150       NA     NA
            AX-3   160       NA     NA'
BB <- read.table(text=BB, header=T)

Some idea to perform it?

like image 482
user2120870 Avatar asked Feb 07 '23 22:02

user2120870


1 Answers

Another way:

lev<-setdiff(as.character(unique(unlist(G[-1]))),NA)
lapply(lev, function(x) {res<-G[-1]==x;res[!res]<-NA;cbind(R[1],res*R[-1])})
like image 74
nicola Avatar answered Feb 16 '23 03:02

nicola