【问题标题】:loop over levels of a factor variable in a function循环函数中因子变量的水平
【发布时间】:2015-01-20 01:56:10
【问题描述】:

我有一个数据框 dat,其中协变量站点被编码为具有 31 个不同级别的因子。

cas_1_sitea_586754968 0 0 1 2 0 sitea 
con_65_sitea_568859302 1 0 2 1 1 siteb
cas_9_siteb_0799700 0 0 0 0 0 siteb 
con_siteb_THR84569 2 0 0 1 0 sitea

当我一次将它应用于一个站点变量时,我有一个可以工作的函数:

get_maf <- function(data){
    allele.count <- apply(data[,1:(ncol(data)-2)],2,sum)
    maf <- allele.count/(2*nrow(data))
    out <- paste((unique(data$site)),"_jp.maf",sep="")
    write.table(maf, out, col.names=F, quote=F)
}

但是,当我尝试像这样使用 lapply 遍历 31 个站点中的每个站点中的数据时:

lapply(unique(dat$site), get_maf, data = dat)    

我收到一个错误:lapply(unique(jp$site), get_maf_jp, data = jp) Error in FUN(c("aber", "ajsz", "asrb", "buls", "cati", "caws", "cims", : unused argument (c("aber", "ajsz", "asrb", "buls", "cati", "caws", "cims", "clo3", "cou3", "denm", "dubl", "edin", "egcu", "ersw", "gras", "irwt", "lie2", "lie5", "mgs2", "msaf", "munc", "pewb", "pews", "s234", "swe1", "swe5", "swe6", "top8", "ucla", "umeb", "umes")[[1]])

非常感谢您对我在这里做错的任何见解。

【问题讨论】:

  • 您的示例不可重现。

标签: r lapply


【解决方案1】:

lapply(unique(dat$site), get_maf, data = dat) 表达式的问题在于它试图将两个参数传递给get_maf:第一个来自lapply,第二个来自data=dat。你可以这样修复它:lapply(unique(dat$site), function(s) {get_maf(data=dat[dat$site==s,]})

或者,您可以使用

library(dplyr)
dat %>% group_by(site) %>% get_maf

PS:如果您正在处理大型数据集,请考虑在 get_maf 函数中使用 allele.count &lt;- colSums(data[,1:(ncol(data)-2)]),而不是现在使用的速度要慢得多的 allele.count &lt;- apply(data[,1:(ncol(data)-2)],2,sum)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    相关资源
    最近更新 更多