【发布时间】:2014-04-23 07:09:54
【问题描述】:
我模拟了一个包含 200 行 x 1000 列的数据矩阵。它在二项分布中包含 0 和 1。 1 出现的概率取决于我创建的概率矩阵。
然后我转置这个数据矩阵并将其转换为数据帧。我创建了一个函数,它将向数据框的每一行引入缺失数据。引入缺失数据后,该函数还会在数据框中添加三列。一列是 1 的 1000 行中每一行的计算频率。第二列是每行中 0 的计算频率。第 3 列是每行中缺失值的频率。
我想用相同的输入数据帧(没有缺失值的那个)重复这个函数 500 次,并输出三个数据帧:一个有 500 列,包含所有计算的 0 频率(每次模拟一列) ,一个包含 500 列包含所有计算的 1 频率,另一个包含 500 列缺失数据频率。
我看到mapply() 用于类似的用途,但不确定它是否适用于我的情况。每次重复该函数时,如何将函数重复应用于数据帧并存储在该函数中执行的每个计算的输出?
谢谢!
####Load Functions####
###Compute freq of 0's
compute.al0 = function(GEcols){
(sum(GEcols==0, na.rm=TRUE)/sum(!is.na(GEcols)))
}
###Compute freq of 1's
compute.al1 = function(GEcols){
(sum(GEcols==1, na.rm=TRUE)/sum(!is.na(GEcols)))
}
#Introduce missing data
addmissing = function(GEcols){
newdata = GEcols
num.cols = 200
num.miss = 10
set.to.missing = sample(num.cols, num.miss, replace=FALSE) #select num.miss to be set to missing
newdata[set.to.missing] = NA
return(newdata) #why is the matrix getting transposed during this??
}
#Introduce missing data and re-compute freq of 0's and 1's, and missing data freq
rep.missing = function(GEcols){
indata = GEcols
missdata = apply(indata,1,addmissing)
missdata.out = as.data.frame(missdata) #have to get the df back in the right format
missdata.out.t = t(missdata.out)
missdata.new = as.data.frame(missdata.out.t)
missdata.new$allele.0 = apply(missdata.new[,1:200], 1, compute.al0) #compute freq of 0's
missdata.new$allele.1 = apply(missdata.new[,1:200], 1, compute.al1) #compute freq of 1's
missdata.new$miss = apply(missdata.new[,1:200], 1, function(x) {(sum(is.na(x)))/200}) #compute missing
return(missdata.new)
}
#Generate a data matrix with no missing values
datasim = matrix(0, nrow=200, ncol=1000) #pre-allocated matrix of 0's of desired size
probmatrix = col(datasim)/1000 #probability matrix, each of the 1000 columns will have a different prob
datasim2 = matrix(rbinom(200 * 1000,1,probmatrix),
nrow=200, ncol=1000, byrow=FALSE) #new matrix of 0's and 1's based on probabilities
#Assign column names
cnum = 1:1000
cnum = paste("M",cnum,sep='')
colnames(datasim2) = cnum
#Assign row names
rnum = 1:200
rnum = paste("L",rnum,sep='')
rownames(datasim2) = rnum
datasim2 = t(datasim2) #data will be used in the transposed form
datasim2 = as.data.frame(datasim2)
#add 10 missing values per row and compute new frequencies
datasim.miss = rep.missing(datasim2)
#Now, how can I repeat the rep.missing function
#500 times and store the output of the new frequencies
#generated from each repetition?
【问题讨论】:
标签: r simulation repeat