这是一个小例子(不完全是,但类似的问题)我想做的事情:
test1 <- data.frame (matrix(sample( c(1,2,3,NA),15, replace = TRUE), 5,3))
X1 X2 X3
1 NA NA 2
2 1 3 3
3 NA 1 NA
4 NA 2 NA
5 2 NA 3
我想用5种不同的种子循环这个过程:1:chr。我希望然后按列结合结果数据框:
X1 X2 X3 X1.1 X2.1 X3.1 ... so on (r will accept two variables with same name)
X1 X2 X3 X1 X2 X3 X1 X2 X3 X1 X2 X3 X1 X2 X3
1 NA NA 2 1 NA NA 2 1 NA NA 2 1 NA NA 2
2 1 3 3 2 1 3 3 2 1 3 3 2 1 3 3
3 NA 1 NA 3 NA 1 NA 3 NA 1 NA 3 NA 1 NA
4 NA 2 NA 3 NA 1 NA 3 NA 1 NA 3 NA 1 NA
5 2 NA 33 NA 1 NA 3 NA 1 NA 3 NA 1 NA
这是我的试用版:
nchr = 1:5
seed <- round(runif(nchr)*1000000)
funct <- function (x){
set.seed <- seed[x]
test1 <- data.frame (matrix(sample( c(1,2,3,NA),15, replace = TRUE), 5,3))
return (test1)
}
sapply(nchr, funct)
我如何实现目标?
答案 0 :(得分:5)
> do.call(cbind, lapply(nchr, funct) )
X1 X2 X3 X1 X2 X3 X1 X2 X3 X1 X2 X3 X1 X2 X3
1 NA 1 2 2 2 1 2 1 2 3 1 NA NA 1 3
2 1 1 3 NA NA NA 3 2 NA 3 1 1 3 2 1
3 3 3 2 2 2 3 2 2 3 1 1 1 2 NA 2
4 1 2 1 2 1 1 NA 2 3 1 2 1 2 2 NA
5 2 2 1 1 1 NA 1 3 2 3 NA 3 3 2 3