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

c6ubokkw  于 2023-05-26  发布在  其他
关注(0)|答案(3)|浏览(140)

我正在尝试根据条件跳过一行代码。这里的示例数据集看起来像。

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"
gcxthw6b

gcxthw6b1#

尝试将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"
6kkfgxo0

6kkfgxo02#

也许就做这样的事

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

vkc1a9a23#

除非您必须使用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"

相关问题