我试图通过创建满足以下条件的向量y,使用样本选择功能从1到100中随机选择10个整数:如果所选整数是偶数 数字,则y返回“偶数”,否则y返回“奇数”。 我尝试了以下代码,但没有得到。]
对此有任何帮助吗? 谢谢
vec<-rnorm (100)
myf <- function(vec){
y =
for (i in vec) {
if (i %% 2 == 0) k <- k + 1
return(y)
}
}
myf(vec)
vec <-rnorm (100)
myf <- function(vec){
y =
for (i in vec) {
if (i %% 2 == 0) k <- k + 1
return(y)
}
}
myf(vec)
答案 0 :(得分:2)
以下两种方法是等效的:
set.seed(123)
# Straight forward
res0 <- sample(x = c("even", "odd"), size = 10, replace = TRUE, prob = c(.5, .5) )
res0
#> [1] "odd" "even" "odd" "even" "even" "odd" "even" "even" "even" "odd"
# as you said
spl <- sample(x = 1:100, size = 10, replace = TRUE )
res1 <- ifelse(spl%%2 == 0, "even", "odd")
res1
#> [1] "even" "even" "even" "even" "odd" "even" "odd" "odd" "odd" "even"