生成的数据集如下:
cn <- c("Cop-1", "Cop-2", "LEW-1", "Lew-3", "Cop-3", "SHR-2", "LEW-2",
"SHRP-3", "SHRP-1")
rn <- paste(rep("Gene_", 4), 1:4, sep = "")
start <- matrix(nrow = 4, ncol = 9)
rownames(start) <- rn
colnames(start) <- cn
start[1, ] <- c(0, .01, 3, 4, 0.001, 11, 5, 15, 46)
start[2, ] <- c(0, .01, 3, 4, 0.001, 11, 5, 15, 46)
start[3, ] <- c(0, .01, 3, 4, 0.001, 11, 5, 15, 46)
start[4, ] <- c(0, .01, 3, 4, 0.001, 11, 5, 15, 46)看起来是这样:
Cop-1 Cop-2 LEW-1 Lew-3 Cop-3 SHR-2 LEW-2 SHRP-3 SHRP-1
Gene_1 0 0.01 3 4 0.001 11 5 15 46
Gene_2 0 0.01 3 4 0.001 11 5 15 46
Gene_3 0 0.01 3 4 0.001 11 5 15 46
Gene_4 0 0.01 3 4 0.001 11 5 15 46`我想扫描这个数据集,并根据以下标准获得一个新的已重新编码的数据集:
如果Gene_n的值对于所有复制(例如SHRP-1、2和3)都是>= 10,那么在一个新的矩阵中,Gene_n的SHRP值将为1。如果对于所有复制(例如Cop-1、2和3),Gene_n的值都小于1,那么在一个新的矩阵中,Gene_n的Cop值将为0。任何其他场景(例如,LEW-1、2和3)都被分配到0.5。
最后的数据集应该如下所示:
cn2 <- c("Cop", "LEW", "SHRP")
end <- matrix(nrow = 4, ncol = 3)
colnames(end) <- cn2
rownames(end) <- rn
end[1, ] <- c(0, 0.5, 1)
end[2, ] <- c(0, 0.5, 1)
end[3, ] <- c(0, 0.5, 1)
end[4, ] <- c(0, 0.5, 1)
Cop LEW SHRP
Gene_1 0 0.5 1
Gene_2 0 0.5 1
Gene_3 0 0.5 1
Gene_4 0 0.5 1谢谢你的帮助。我尝试过使用拆分函数和dplyr,但是没有能够得到想要的结果。我通过搜索找到了这个问题,并且ot (Split data frame based on column name pattern and then rebind into 1 data frame)使我接近了,但同样,与我所需要的结果不太接近。
谢谢你的帮助。
发布于 2017-11-22 19:53:26
cn2 <- c("Cop", "LEW", "SHRP")
end <- sapply(cn2, function(x){
cols <- grep(paste0('^', x, '-', '[1-9]+'), colnames(start))
apply(start[, cols], MARGIN =1, function(y) {
if(all(y >= 10, na.rm = T)) return(1)
if(all(y <1, na.rm = T)) return(0)
return(0.5)
})
})
rownames(end) <- rn
Cop LEW SHRP
Gene_1 0 0.5 1
Gene_2 0 0.5 1
Gene_3 0 0.5 1
Gene_4 0 0.5 1https://stackoverflow.com/questions/47441561
复制相似问题