R语言作业,求问代码怎么写

2024-12-16 06:07:55
推荐回答(1个)
回答1:

R语言作业,求问代码怎么写 

1)
set.seed(1)

n = 5000
gender = sample(c("f","m"),size = n, TRUE)

dechot = function(gender, type){
n = length(gender)
list = c(NA,n)
for (i in 1:n){
list[i] = switch(gender[i], "f"=type[1], "m"=type[2])
}
return(list)
}

type = c(0,1)
dechot(gender, type)

2)
set.seed(1)
n = 100000
A = floor(runif(n,0,n))

search = function(vector){
n = length(vector)
two = three = number = NA
for (i in 1:n){
if (vector[i]%%2 == 0)

two = rbind(two,vector[i])

if(vector[i]%%3 == 0)

three = rbind(three,vector[i])

}
two.new = two[-1]
three.new = three[-1]
n.two = length(two.new)
n.three = length(three.new)
n.six = length(two.new[two.new%%6 == 0])
number = n.two +n.three-n.six

return(list(c(two.new=two.new, three.new=three.new, number = number)))
}

result = search(A)

result$two.new
result$three.new
result$number