首页 > 解决方案 > R for循环忽略条件if语句

问题描述

我正在使用一个数据集,如果值不丢失,我需要 R 跳过它。我试过制作一个 for 循环,但 R 忽略了我的逻辑。我看过其他 for 循环帖子,但它们不涉及条件被忽略。

这是一个示例数据集:

library(dplyr)
  my_problem <- tibble(name = c("Joe", "Joseph", "Joey"),
                       score1 = c(2, 7, 12),
                       score2 = c(NA, 5, 10))

这是我想要的样子:

solution <- tibble(name = c("Joe", "Joseph", "Joey"),
                     score1 = c(1, 7, 12),
                     score2 = c(NA, 5, 10),
                     score2edit = c(.30103, 5, 10))

如果 score2 列是 NA,这是我的 for 循环,在 score1 上进行 log10() 转换。但是,由于某种原因,代码忽略了我的 if 语句并直接跳转到 else。

  for(i in 1:nrow(my_problem)) {
    if(is.na(my_problem$score2[i])) {
      my_problem$score2edit <- log10(my_problem$score1)
    } else {
      my_problem$score2edit <- my_problem$score2
    }
  }

谢谢!如果您还可以解释为什么此循环不起作用,那将非常有帮助。

标签: rfor-loopif-statementconditional-statementsna

解决方案


我们可以使用矢量化选项 ( ifelse/if_else/case_when)

library(dplyr)
my_problem %>% 
    mutate(score2edit = case_when(is.na(score2) ~ log10(score1), TRUE ~ score2))
# A tibble: 3 x 4
#  name   score1 score2 score2edit
#  <chr>   <dbl>  <dbl>      <dbl>
#1 Joe         2     NA      0.301
#2 Joseph      7      5      5    
#3 Joey       12     10     10   

循环遍历每一行,因此for如果我们使用它然后对整个数据集进行分配/替换,则每一行中的整列都会被替换


推荐阅读