r - 使用数值条件对一系列列进行编码

我有一系列数字列,范围从 0 到 8。当一行仅一次报告 3 或更多时,我想创建一个二项式变量,而不是编码为“高”,否则为“低”。

structure(list(AE_1 = c(0L, 1L, 0L, 0L, 0L, 2L, 0L), AE_2 = c(0L, 
1L, 2L, 1L, 0L, 0L, 0L), AE_3 = c(1L, 4L, 1L, 8L, 0L, 8L, 1L), 
    AE_4 = c(0L, 1L, 1L, 0L, 0L, 0L, 0L), AE_5 = c(0L, 0L, 1L, 
    1L, 0L, 0L, 1L), AE_6 = c(0L, 5L, 1L, 3L, 0L, 4L, 1L), AE_7 = c(0L, 
    1L, 1L, 1L, 0L, 2L, 0L), AE_8 = c(0L, 2L, 1L, 2L, 0L, 0L, 
    0L), new_AE = c("low", "low", "low", "low", "low", "low", 
    "low")), class = "data.frame", row.names = c(NA, -7L))

我有这段代码,所有行的结果都很低。


df<-df%>%
     mutate(new_AE=  pmap_chr(select(., starts_with('AE')), ~ 
       case_when(any(c(...) <= 2) ~ "low" , any(c(...) >=3) ~ "high")))

虽然我想要这样的东西:

最佳答案

这可以通过使用 pmax 检查 base R 中每一行的最大值来轻松完成。现在当然,您不会将 8 个列名称写入 pmax,所以这样做吧。

df[,9] <- c("low", "high")[ 1 + (do.call(pmax, df[,-9]) >= 3)]

> df
  AE_1 AE_2 AE_3 AE_4 AE_5 AE_6 AE_7 AE_8 new_AE
1    0    0    1    0    0    0    0    0    low
2    1    1    4    1    0    5    1    2   high
3    0    2    1    1    1    1    1    1    low
4    0    1    8    0    1    3    1    2   high
5    0    0    0    0    0    0    0    0    low
6    2    0    8    0    0    4    2    0   high
7    0    0    1    0    1    1    0    0    low

请参阅 [] 中的 expr 根据您想要的条件返回 true/false

# this returns max of each row
do.call(pmax, df[,-9])
[1] 1 5 2 8 0 8 1

# this checks whether max of each row is 3 or more
do.call(pmax, df[,-9]) >= 3
[1] FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE

因此,如果您不习惯使用此策略,可以改用replace

df$new_AE <- replace(df$new_AE, do.call(pmax, df[,-9]) >= 3, "high")

https://stackoverflow.com/questions/67442895/

相关文章:

regex - 如何将 RegEx token 传递给 RegEx 替换中的 PowerShell

amazon-web-services - CloudFormation YAML - 带有条件语句

python - 将 VSCode 更新到 1.56.1 后,出现错误 : "Cannot acti

r - 将列中以冒号分隔的字符串拆分为 R 中的不同列

python - 有没有办法缩短多个 if 语句?

fortran - Fortran 中的嵌套名单

c++ - 在 C++ 中定义类枚举值的 std::vector 的缩写语法

visual-studio-code - 删除 VSCode 中的 Sublime 文本主题

python - 基于字典值映射Python列表

reactjs - 创建一个可以通过函数调用显示的 React 组件(如 react-toastif