首页 > 解决方案 > 嵌套 if / else if 以多个列值为条件 - R

问题描述

目标是根据多个条件填充一个新列 (df$final.count)。下面的示例数据框:

structure(list(item = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
2L, 2L, 2L), .Label = c("a", "b"), class = "factor"), raw.count = c(16, 
300, 203, 6, 5, 40, 20, 16, 300, 203), loc = structure(c(4L, 
2L, 2L, 2L, 2L, 3L, 3L, 4L, 2L, 3L), .Label = c("  ", "in", "out", 
"NA"), class = "factor"), side = structure(c(4L, 2L, 3L, 2L, 
3L, 4L, 3L, 4L, 2L, 4L), .Label = c("F", "L", "R", "NA"), class = "factor"), 
    recount = c(15, NA, NA, 7, NA, NA, 16, 15, NA, NA), final.count = c(NA_real_, 
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
    NA_real_, NA_real_, NA_real_), EXPECTED = c(15, 60, 120, 
    7, 5, 40, 16, 15, 300, 203)), row.names = c(NA, 10L), class = "data.frame")

目标是根据影响多个列的以下条件填充新列 (df$final.count):

  1. 如果 df$recount 中有一个数字,则应在 df$final.count 中使用 df$recount 对其他列值无条件
  2. 如果 df$recount AND df$raw.count > 10 AND df$loc is "in" AND df$side is "L" THAN function 0.2*df$raw.count 中没有数字 (NA) 应该用于填充df$final.count
  3. 如果 df$recount AND df$raw.count > 10 AND df$loc is "in" AND df$side is "R" THAN function 0.6*df$raw.count 中没有数字 (NA) 应该用于填充df$final.count (注意只有一面不同)
  4. 如果 df$raw.count =<10 则应使用 df$raw.count 如果以上 1 成立
  5. 如果 df$loc 为“out”,则 df$final.count <- df$raw.count 无条件对其他列值除外,如果上述 1 成立

我在循环中尝试了各种版本的 if / else if,例如:

  for (i in 1:nrow(df)) {
  if(!is.na(df$recount[i]) {
    df$final.count <- df$recount
  }
  else if(df$item[i] == "a" & df$raw.count[i] > 10 & df$loc[i] == "in" & df$side[i] == "L") {
    df$final.count <- 0.2*df$raw.count[i]
  }
  else if(df$item[i] == "a" & df$raw.count[i] > 10 & df$loc[i] == "in" & df$side[i] == "R") {
    df$final.count <- 0.6*df$raw.count[i]
  }
  else if(df$raw.count <= 10){
    df$final.count <- df$raw.count
  }
  else(df$loc == "out") {
    df$final.count <- df$raw.count
  }
}

标签: r

解决方案


如果您使用case_when()dplyr-package 中的 a,它会变得更具可读性..您也可以松开for.

library( dplyr )
df %>%
  mutate( final.cond = case_when(
    !is.na( recount ) ~ recount,
    item == "a" & raw.count > 10 & loc == "in" & side == "L" ~ 0.2 * raw.count,
    item == "a" & raw.count > 10 & loc == "in" & side == "R" ~ 0.6 * raw.count,
    raw.count <= 10 ~ raw.count,
    loc == "out" ~ raw.count,
    TRUE ~ as.numeric(NA)
  ))

推荐阅读