r - 嵌套 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):
- 如果 df$recount 中有一个数字,则应在 df$final.count 中使用 df$recount 对其他列值无条件
- 如果 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
- 如果 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 (注意只有一面不同)
- 如果 df$raw.count =<10 则应使用 df$raw.count 如果以上 1 成立
- 如果 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
}
}
解决方案
如果您使用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)
))
推荐阅读
- jquery - java.io.FileNotFoundException:SRVE0190E:找不到文件:/mdta/app/js/jquery.mobile-1.4.2.min.map
- azure - 使用应用程序权限调用 Microsoft Graph privilegedOperationEvents 时出错
- c++ - 具有物理表示的所有权
- laravel - 上传文件时,laravel 会显示 PostTooLargeException 什么是处理这个问题的解决方案
- r - 如何首先转置一个矩阵,然后用 0 填充缺失月份的值
- powershell - 将 System.Text.RegularExpressions.Regex 作为 Powershell 6 中的函数参数传递
- json - 使用python将数据写入json文件
- io - VM 主机上的慢 I/O
- angular - Angular:SyntaxError:意外的令牌{
- android-studio - 如何从 Sqlite 数据库中选择特定范围的行(例如 20 到 30)然后随机化它们