在 R 中满足条件时跳过一行代码

Skipping a line of code when a condition is met in R

我正在尝试根据条件跳过一行代码。我的示例数据集如下所示。

df <- data.frame(
  id = c(12,25,31,47),
  b = c("cat.1","cat.2","cat.3","cat.2"),
  drop = c(FALSE,TRUE,TRUE,TRUE))

> df
  id     b  drop
1 12 cat.1 FALSE
2 25 cat.2  TRUE
3 31 cat.3  TRUE
4 47 cat.2  TRUE

基于 bdrop 变量,我打印不同的 out 并将它们组合在 output 中。当 drop = FALSE.

我想跳过一行代码
output <- c()
for(i in 1:nrow(df)) {
  if (df$b[i] == "cat.1") {
    out <- paste0("Item_first_",df$id[i],"_",df$drop[i])
    
  } else if(df$b[i] == "cat.2") { 
    out <- paste0("Item_second_",df$id[i],"_",df$drop[i])
    
  } else {
    out <- paste0("Item_others_",df$id[i],"_",df$drop[i])
  }
  output <- c(output, out) 
}

print(output)
[1] "Item_first_12_FALSE" "Item_second_25_TRUE" "Item_others_31_TRUE" "Item_second_47_TRUE"

在这种情况下,需要从输出中删除 "Item_first_12_FALSE",因为数据集中的这一行具有 drop=FALSE.

我知道在 for() 循环中有 next 函数,但它避免了整个迭代。而且,通过从数据集中删除 FALSE 看起来很容易修复,但由于其他条件组合,我特别想在 ifelse 中省略它。在这种情况下,我只需要跳过满足 drop=`FALSE' 条件的这一部分。

 if (df$b[i] == "cat.1") {
    out <- paste0("Item_first_",df$id[i],"_",df$drop[i])
    
  }

所需的输出将是:

"Item_second_25_TRUE" "Item_others_31_TRUE" "Item_second_47_TRUE"

尝试将您的 if-else 包装在另一个 if 语句中:

output <- c()
for(i in 1:nrow(df)) {
  if (df$drop[i] == T) {
    if (df$b[i] == "cat.1") {
      out <- paste0("Item_first_",df$id[i],"_",df$drop[i])
      
    } else if(df$b[i] == "cat.2") { 
      out <- paste0("Item_second_",df$id[i],"_",df$drop[i])
      
    } else {
      out <- paste0("Item_others_",df$id[i],"_",df$drop[i])
    }
    output <- c(output, out)
  }  
}
> print(output)
[1] "Item_second_25_TRUE" "Item_others_31_TRUE" "Item_second_47_TRUE"

也许就做这样的事情

with(df, sprintf("Item_%s_%d_%s", dplyr::case_when(b == "cat.1" ~ "first", b == "cat.2" ~ "second", TRUE ~ "others"), id, drop)[drop])

除非你必须有 for 循环

output <- unlist(ifelse((df$b == "cat.1"),list(NULL),paste("Item_second_",df$id,df$drop, sep="_")))

print (output)
#  "Item_second__25_TRUE" "Item_second__31_TRUE" "Item_second__47_TRUE"