[英]R How to sample a list of data.frame, with vector as sampling size
I have a list of data.frames : 我有一个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"))))
How to sample theses data.frames and adjust sampling size according to vector s : 如何对这些数据进行采样,并根据向量s调整采样大小:
s <- c(1,2,3,1)
So for ldf[[1]]
, I would get : 因此对于ldf[[1]]
,我会得到:
ldf[[1]][sample(nrow(ldf[[1]]),size=1),]
for ldf[[2]]
, I would get : 对于ldf[[2]]
,我会得到:
ldf[[2]][sample(nrow(ldf[[2]]),size=2),]
ect...... 等等……
How to wrap this in an lapply call, I guess something close to : 如何将其包装在一个调用中,我猜有些接近:
lapply(ldf,function(x) x[sample(nrow(x),s),]) # but it's not sampling according to sizes values in s
You can use mapply
( as mentioned by @Justin) like this: 您可以像这样使用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 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.