我有一个data.frames列表:
ldf <- list(structure(c(2, 0.15, 0.52, 5, 6, 2, 1), .Dim = c(1L, 7L), .Dimnames = list(
"M01", c("fitness", "cMRc", "cMRcg", "pMR", "cMEnr", "gMR",
"sex"))), structure(c(4, 4, 9, 0.22, 0.19, 0.05, 0.555, 0.495,
0.605, 8, 7, 4, 15, 10, 4, 3, 3, 3, 1, 1, 1), .Dim = c(3L, 7L
), .Dimnames = list(c("M03", "M06", "M12"), c("fitness", "cMRc",
"cMRcg", "pMR", "cMEnr", "gMR", "sex"))), structure(c(4, 4, 7,
7, 0.145, 0.09, 0.2, 0.195, 0.46, 0.68, 0.45, 0.48, 6, 3, 7,
5, 8, 3, 10, 9, 4, 4, 4, 4, 1, 1, 1, 1), .Dim = c(4L, 7L), .Dimnames = list(
c("M05", "M08", "M09", "M10"), c("fitness", "cMRc", "cMRcg",
"pMR", "cMEnr", "gMR", "sex"))), structure(c(10, 10, 0.145,
0.18, 0.725, 0.4, 6, 5, 9, 5, 5, 5, 1, 1), .Dim = c(2L, 7L), .Dimnames = list(
c("M02", "M04"), c("fitness", "cMRc", "cMRcg", "pMR", "cMEnr",
"gMR", "sex"))))
如何根据矢量s对样本data.frames进行采样并调整采样大小:
s <- c(1,2,3,1)
因此对于ldf[[1]]
,我会得到:
ldf[[1]][sample(nrow(ldf[[1]]),size=1),]
对于ldf[[2]]
,我会得到:
ldf[[2]][sample(nrow(ldf[[2]]),size=2),]
ECT ......
如何在一个lapply调用中包装它,我想有些接近:
lapply(ldf,function(x) x[sample(nrow(x),s),]) # but it's not sampling according to sizes values in s
答案 0 :(得分:1)
您可以使用mapply
(如@Justin所述):
f <- function(x,y){
rep <- y > nrow(x) ## repeat if y > nrow(x)
x[sample(nrow(x),size=y,rep=rep),]
}
s <- c(1,2,3,1)
mapply(FUN=f,ldf,s )