私は一連の被験者に対する一連の薬物による治療の結果が一連の病院で測定されたデータを持っています。 (#drugs> #subjects> #hospitals)マトリックスを効率的に充填する
マイdata.frame
は、各行ごとにdrug
、subject
、hospital
、outcome
組み合わせてい
subjects <- paste("S",1:100,sep="_")
drugs <- paste("D",1:1000,sep="_")
:
df <- expand.grid(subject=subjects,drug=drugs,stringsAsFactors=F)
hospitals <- paste("H",1:10,sep="_")
df$hospital <- rep(sapply(hospitals,function(h) rep(h,10)),200)
set.seed(1)
df$outcome <- runif(nrow(df),0,100)
は、今私はmatrix
それぞれを構築したいが行はユニークなhospital
subject
の組み合わせであり、各列は固有のhospital
drug
の組み合わせです。ここでは、おそらくこの行列を構築するためのない最適に効率的な方法です:
df$hospital.subject <- paste(df$hospital,df$subject,sep=":")
df$hospital.drug <- paste(df$hospital,df$drug,sep=":")
hospital.subject <- unique(paste(df$hospital,df$subject,sep=":"))
hospital.drug <- unique(paste(df$hospital,df$drug,sep=":"))
mat <- do.call(rbind,lapply(hospital.subject, function(x){
hospital.subject.df <- dplyr::filter(df,hospital.subject==x)
res <- rep(NA,length(hospital.drug))
match.idx <- match(hospital.drug,hospital.subject.df$hospital.drug)
res[which(!is.na(match.idx))] <- hospital.subject.df$outcome[match.idx[which(!is.na(match.idx))]]
return(res)
}))
rownames(mat) <- hospital.subject
colnames(mat) <- hospital.drug
そこで質問#1がより効率的にこれが可能である場合は、この行列を構築する方法です。今
、マトリックスは、私はこれらのsubjects
がから、それらが観察されたhospital.drug
の組み合わせに応じて、観察されなかった中で、すなわち、そのhospital.drug
組み合わせて、欠損値と各hospital.subject
組み合わせを転嫁したいのですが希薄であるため、 mean
= median
およびsd
= mad
のこれらの観察されたhospital.subject
組み合わせの正規分布。すなわち
は、hospitals[1]
のみで観察されたsubjects[1:10]
、たとえばため、各drug
ためhospitals[1]
からhospitals[2:10]
ために埋めます。それは意味:
mat[1:10,2:10] <- rnorm(90,median(mat[1:10,1]),mad(mat[1:10,1]))
mat[1:10,12:20] <- rnorm(90,median(mat[1:10,1]),mad(mat[1:10,1]))
ので、1と次病院(マット内の行)のために、例えば、for
ループを使用して
mat[31:40,2:10] <- rnorm(90,median(mat[31:40,1]),mad(mat[31:40,1]))
mat[31:40,12:20] <- rnorm(90,median(mat[31:40,1]),mad(mat[31:40,1]))
私はこのようにしたいと思う:
for(h in 1:length(hospitals)){
row.idx <- which(grepl(paste0(hospitals[h],":"),hospital.subject)==T)
col.idx <- which(grepl(paste0(hospitals[h],":"),hospital.drug)==T)
for(i in 1:length(col.idx)){
drug <- strsplit(hospital.drug[col.idx[i]],split=":")[[1]][2]
impute.idx <- which(grepl(paste0(":",drug,"$"),hospital.drug,perl=T)==T)[-col.idx[i]]
mat[row.idx,impute.idx] <- rnorm(length(row.idx)*length(impute.idx),mean=median(mat[row.idx,col.idx[i]]),sd=mad(mat[row.idx,col.idx[i]]))
}
}
これを達成するためのより効率的でエレガントな方法がありますか?
私の実際のデータは、各病院の被験者の数が同一ではないという意味でこの例よりも組織化されておらず、さらに複数の病院で同じ薬剤で治療されている被験者。
私は私の質問で記述している方法を教えているとは思わない – dan