我想创建一个循环来重复数据集列表中的代码行。每个数据集如下所示:
gwas_1
ID p
1 0.0000005
2 0.0123474
...
gwas_2
ID p
1 0.0000055
2 0.5854587
... 因此,我想创建一个新列,并在每个数据集中的新列中检查频率。我以前是这样做的
data=gwas_1
data$p_threshold <- ifelse(data$p<0.001, 1, 0)
table (data$p_threshold)
data=gwas_2
data$p_threshold <- ifelse(data$p<0.001, 1, 0)
table (data$p_threshold) 但意识到这可能不是很有效。你能帮我创建一个循环吗,因为我的循环不工作(“错误:$ operator对于原子向量无效”):
list=c("gwas_1, gwas_2, gwas_3")
for (db in list){
db$p_threshold <- ifelse(db$p<0.001, 1, 0)
table (db$p_threshold)
}发布于 2018-11-21 21:55:57
试试这个:
设置数据:
set.seed(1337)
tmp <- data.frame(p = runif(100)*.007)
l1 <- list(gwas_1 = tmp, gwas_2 = tmp, gwas_3 = tmp)代码:
lapply(l1, function(x) table(+(x[["p"]]<0.001)))结果:
#$gwas_1
#
# 0 1
#88 12
#
#$gwas_2
#
# 0 1
#88 12
#
#$gwas_3
#
# 0 1
#88 12 像l1)
lapply一样,
已经:比ifelse快大约15倍
#> set.seed(1337)
#> tmp<-data.frame(p = runif(99999999)*.007)
#> microbenchmark::microbenchmark(+(tmp[["p"]]<0.001) , ifelse(tmp[["p"]]<0.001, 1, 0), times = 4)
#Unit: milliseconds
# expr min lq mean median uq max neval cld
# +(tmp[["p"]] < 0.001) 463.054 527.4309 1779.396 1440.110 3031.362 3774.312 4 a
# ifelse(tmp[["p"]] < 0.001, 1, 0) 7071.470 7140.4354 8021.247 7887.672 8902.058 9238.173 4 bhttps://stackoverflow.com/questions/53413437
复制相似问题