我用 R 编写了以下代码:
Gems <- data.frame(
Color = c("Red", "Blue", "Purple", "Orange",
"Green", "Pink", "White", "Black", "Yellow"),
Weight = round(runif(9,0.5,5),2),
Value = round(abs(rnorm(9,0,5))+0.5,2)
)
InitilzePop <- function(size){
pop <- (t(sapply(1:size, function(pop) round(runif(nrow(Gems),0, 1), 0))))
colnames(pop)<- Gems$Color
return(pop)
}
我想更改这部分代码
round(runif(nrow(Gems),0, 1), 0)
,而不是生成随机值,而是根据向量中的Gems
的大小获取值,例如,
vector <- c(1,1,0,0,0,1,0,1,0,0,1,1,1,0,0,0,0,1,1,1,
1,1,0,0,1,1,1,0,0,1,1,1,0,0,1,1,1,0) # ...
并且从向量中获取的值集每次都是新的。当前和想要的输出是相同的,唯一的区别是值的来源:
Red Blue Purple Orange Green Pink White Black Yellow
[1,] 0 0 0 1 0 0 0 1 1
[2,] 1 0 1 1 0 1 1 1 0
[3,] 1 0 0 1 0 0 0 1 0
[4,] 1 0 0 1 0 0 0 0 0
[5,] 1 1 1 0 0 0 1 0 1
[6,] 1 0 0 1 0 1 0 0 0
您在寻找
base::sample()
吗?
set.seed(123)
Gems <- data.frame(
Color = c("Red", "Blue", "Purple", "Orange",
"Green", "Pink", "White", "Black", "Yellow"),
Weight = round(runif(9, 0.5, 5), 2),
Value = round(abs(rnorm(9, 0, 5)) + 0.5, 2)
)
myvector <- c(1,1,0,0,0,1,0,1,0,0,1,1,1,0,0,0,0,1,1,1,
1,1,0,0,1,1,1,0,0,1,1,1,0,0,1,1,1,0)
urvector <- c(1,1,0,0,0,1,0,1,0,0,1,1,1,0,0,0,0,1,1,1,
1,1,0,0,1,1,1,0,0,1,1,1,0,0,1,1,1,0) * 2
InitilzePop <- function(size, df, vec = NULL, repl = TRUE){
if (is.null(vec)) {
pop <- (t(sapply(1:size, function(pop) round(runif(nrow(df),0, 1), 0))))
} else {
pop <- (t(sapply(1:size, function(pop) round(sample(vec, nrow(df),
replace = repl), 0))))
}
colnames(pop)<- df$Color
return(pop)
}
InitilzePop(2, Gems)
#> Red Blue Purple Orange Green Pink White Black Yellow
#> [1,] 1 0 0 1 1 1 1 0 0
#> [2,] 1 0 0 0 0 0 0 0 0
InitilzePop(2, Gems, myvector)
#> Red Blue Purple Orange Green Pink White Black Yellow
#> [1,] 0 0 0 1 0 1 1 0 1
#> [2,] 0 0 0 1 1 1 1 0 1
InitilzePop(2, Gems, urvector)
#> Red Blue Purple Orange Green Pink White Black Yellow
#> [1,] 2 0 2 0 2 2 0 2 2
#> [2,] 2 2 2 2 0 0 0 2 0
创建于 2024-04-01,使用 reprex v2.0.2