我有一个接受两个参数(列)的函数。该函数根据另一列中的值 (y) 更改一列 (x) 的值。
fun <- function(x, y) {
x = coalesce(case_when(y %in% c("hello", "hi") ~ '1',
y == "thanks" ~ '2'), x)
}
但是,这需要在许多列对上完成,为什么我想让它成为一个函数。
这是正确的做法吗:
df %>% mutate(across(c(col1, col3), c(col2, col4), fun))
从
col1 col2 col3 col4
1 1
2 4
5 "hello" 5 "hello"
3
4 4
5 "hi" 5 "thanks"
5 "thanks"
5 "goodbye" 5 "hello"
到
col1 col2 col3 col4
1 1
2 4
1 "hello" 1 "hello"
3
4 4
1 "hi" 2 "thanks"
2 "thanks"
5 "goodbye" 1 "hello"