# 在 R 中的資料幀中按行查詢最大絕對值

Lasha Khintibidze 2021年7月14日

## 使用自定義函式在 R 資料框中按行查詢最大絕對值

``````abs_max <- function(data) {
tmp <- Filter(is.numeric, data)
if(inherits(data, "tbl_df")) {
tmp <- as.matrix(tmp)
}
tmp[cbind(1:nrow(tmp), max.col(replace(x <- abs(tmp), is.na(x), -Inf)))]
}

df1 <- data.frame(
id = c("foo", "bar", "goo"),
val_a =  c(-51, 15, 19),
val_b = c(NA, 122, 35),
val_c = c(10, -23, 4)
)

df1\$abs_max = abs_max(df1)
df1
``````

``````id val_a val_b val_c abs_max
1 foo   -51    NA    10     -51
2 bar    15   122   -23     122
3 goo    19    35     4      35
``````

``````library(tibble)

abs_max <- function(data) {
tmp <- Filter(is.numeric, data)
if(inherits(data, "tbl_df")) {
tmp <- as.matrix(tmp)
}
tmp[cbind(1:nrow(tmp), max.col(replace(x <- abs(tmp), is.na(x), -Inf)))]
}

tb1 <- tibble(
id = c("foo", "bar", "goo"),
val_a =  c(-51, 15, 19),
val_b = c(NA, 122, 35),
val_c = c(10, -23, 4)
)

tb1\$abs_max = abs_max(tb1)
tb1
``````

``````# A tibble: 3 x 5
id    val_a val_b val_c abs_max
<chr> <dbl> <dbl> <dbl>   <dbl>
1 foo     -51    NA    10     -51
2 bar      15   122   -23     122
3 goo      19    35     4      35
``````