R:仅用于循环更新向量中的最后一个元素

时间:2018-08-07 05:59:04

标签: r for-loop if-statement

我遵循的逻辑是;

->创建具有1000个元素的结果向量

->使用for循环,该循环将在每次迭代时将旧样本值“ sorting_hat”替换为新值

->使用if else语句用依赖于新采样值“ sorting_hat”的字符串替换结果向量中的第i次迭代

all_student_houses <- rep(0, 1000)
total_students = 1000
student_number = 1


for (student_number in total_students) {

  sorting_hat <- sample(x = 1:4, size = 1, replace = TRUE, prob = c(9/41, 8/41, 14/41, 10/41) )

  if (sorting_hat == 1) {
    all_student_houses[student_number] <- "Slytherin"
    } else if (sorting_hat == 2) {
    all_student_houses[student_number] <- "Gryffindor"
    } else if (sorting_hat == 3) {
    all_student_houses[student_number] <- "Ravenclaw"
    } else {
    all_student_houses[student_number] <- "Hufflepuff"
    }

  }

运行此命令后,我的向量输出为:

>all_student_houses
[995] "0"         "0"         "0"         "0"         "0"         "Slytherin"

我希望此向量的每个元素都可以被ifelse语句中的四个字符串之一代替,而不仅仅是最后一个元素。当前是什么让我绊倒?

4 个答案:

答案 0 :(得分:1)

尝试:

 for (student_number in 1:total_students)

您应为 for循环指定范围。

答案 1 :(得分:1)

我们可以在此处尝试使用ifelse,但是使用case_when软件包中的dplyr可能更干净:

sorting_hat <- sample(x = 1:4, size = 1000, replace = TRUE, prob = c(9/41, 8/41, 14/41, 10/41))
all_student_houses <-
case_when (
    sorting_hat == 1 ~ "Slytherin",
    sorting_hat == 2 ~ "Gryffindor",
    sorting_hat == 3 ~ "Ravenclaw",
    TRUE ~ "Hufflepuff"
)

这里最重要的一点是,如果不需要,您不需要使用循环,因为有ifelsecase_when等矢量化选项可用。

答案 2 :(得分:1)

您可以通过将代码替换为以下代码来优化代码

#Create a named vector 
student_number <- c('Slytherin' = 1,'Gryffindor' = 2, 'Ravenclaw' = 3,
                     'Hufflepuff' = 4)
#Create all the random numbers together
sorting_hat <- sample(x = 1:4, size = 1000, replace = TRUE, 
                         prob = c(9/41, 8/41, 14/41, 10/41))
#Replace it with names
all_student_houses <- names(student_number[sorting_hat])

#Check output
head(sorting_hat)
#[1] 2 2 2 4 3 2

head(all_student_houses)
#[1] "Gryffindor" "Gryffindor" "Gryffindor" "Hufflepuff" "Ravenclaw"  "Gryffindor"

答案 3 :(得分:0)

现在,您的for循环运行一次。您应该使用:

for (student_number in seq(1:total_students)) {
   ...
}