如果条件为/则嵌套在多个列值上-R

时间:2018-12-05 07:37:54

标签: 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 $ recount,则应在df $ final.count中使用,而无其他列值的条件
  2. 如果df $ recount和df $ raw.count中没有数字(NA)> 10并且df $ loc是“ in”并且df $ side是“ L”,则函数0.2 * df $ raw.count应该为用于填充df $ final.count
  3. 如果df $ recount和df $ raw.count中没有数字(NA)> 10并且df $ loc为“ in”且df $ side为“ R”,则函数0.6 * df $ raw.count应为用于填充df $ final.count(仅注意一侧不同)
  4. 如果df $ raw.count = <10,且大于1则应使用df $ raw.count
  5. 如果df $ loc比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
  }
}

1 个答案:

答案 0 :(得分:1)

如果您使用dplyr软件包中的case_when(),它会变得更具可读性。您也可以松开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)
  ))