在R中,我有一个包含30000+行(即数据集群)和100个列(这些列是发生在其中的示例/控件)的数据。
如果任何控件值不是0,则低于编辑的示例值:该行的控件值的两倍必须变为0。
可以将控件值修改为0或保持不变:过滤数据后将删除这些列。
dataframe如下所示:
sampleID <- c('clust1', 'clust2', 'clust3')
sample1 <- c(50, 0, 70)
sample2 <- c(0,40,5)
sample3 <- c(10,20,0)
control1 <- c(10,2,0)
control2 <- c(0,30,0)
df <- data.frame(sampleID, sample1, sample2, sample3, control, control)
df
ClusterID sample1 sample2 sample3 control control
clust1 50 0 10 10 0
clust2 0 40 20 2 30
clust3 70 5 0 0 0 所需的输出应该如下所示:
df
ClusterID sample1 sample2 sample3 control control
clust1 50 0 0 0 0
clust2 0 0 0 0 0
clust3 70 5 0 0 0我尝试过的(不成功的)
#list controls
neg_control = c("control1", "control2")
rows_to_replace = list()
sapply(neg_control, function(nc) {
temp <- df[df[,nc] > 0, ]
#go over values to filter on
values <- temp[,nc]
# go over the values and the rows
sapply(1:length(values), function(i){
# for every column check if the value is twice that of the control
sapply(2:length(colnames(temp)), function(col){
if (temp[i,col] < 2*values[i]){
# if true, change that avalue to 0
temp[i,col] <- 0}
})
# save row to variable
rows_to_replace <- append(rows_to_replace, temps)
})})最后一行生成我需要的行,但我不知道如何将它绑定到我想要的输出中。这段代码返回两个矩阵,而不是我想要的输出。
我和R合作的时间不长,我需要在生物信息学项目中得到正确的结果。我一直在想这件事,一天都在谷歌上搜索,没什么运气。希望这里有人能帮忙!
编辑:运行他的代码工作(经过一个小的编辑)
# control columns ans sample columns
controls = c('control1', 'control2')
samples = c('sample1','sample2','sample3')
# mcr = max control value for each row
mcr <- do.call(pmax, otu[controls])
#mcp = max control values that are positive
mcp <- mcr > 0
# for each row change values that are lower than 2*max control value to 0
otu[mcp, samples][otu[mcp,samples] < 2*mcr[mcp]] <- 0 发布于 2020-07-22 19:55:25
根据所显示的条件
nm1 <- names(df)[startsWith(names(df), 'control')]
mx <- do.call(pmax, df[nm1])
i1 <- mx > 0
nm2 <- grep("^sample\\d+$", names(df), value = TRUE)
df[i1, nm2][df[i1, nm2] < 2 * mx[i1]] <- 0https://stackoverflow.com/questions/63042028
复制相似问题