Subsetting one matrix based in another matrix

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-05 16:53:18

We subset the 'G' from the 2nd column, convert to matrix, and split the sequence with the values in that, create a new matrix with NA ("G1") and using the index, we replace the values that corresponds to the "R" dataset values.

lapply(split(seq_along(as.matrix(G[-1])), 
       as.matrix(G[-1])), function(x) {
        G1 <- matrix(NA, ncol=ncol(G)-1, nrow=nrow(G), 
                   dimnames=list(NULL, names(G)[-1]))
        G1[x] <- as.matrix(R[-1])[x]
        data.frame(pr_id=R$pr_id, G1) })
#$AA
#  pr_id sample1 sample2 sample3
#1  AX-1      NA     120     130
#2  AX-2      NA      NA      NA
#3  AX-3      NA      NA     196

#$AB
#  pr_id sample1 sample2 sample3
#1  AX-1     100      NA      NA
#2  AX-2      NA     180      NA
#3  AX-3      NA     120      NA

#$BB
#  pr_id sample1 sample2 sample3
#1  AX-1      NA      NA      NA
#2  AX-2     150      NA      NA
#3  AX-3     160      NA      NA

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])})
row.names(R) <- R[[1]]; R <- as.matrix(R[-1])
row.names(G) <- G[[1]]; G <- as.matrix(G[-1])
AA <- ifelse(G=="AA", R, NA)
AB <- ifelse(G=="AB", R, NA)
BB <- ifelse(G=="BB", R, NA)

or with lapply() (for the last three lines):

lapply(c("AA", "AB", "BB"), function(x) ifelse(G==x, R, NA))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!