更新时间:2023-02-18 11:20:16
非常好的问题.谢谢!
这里我们使用:
rowSums
添加一列,行和为 X1-X3mutate
跨
所有X
和coalesce
每个 X
与 rowSum1
rowSum1
列因为不需要而消失了 ->.keep="unused"
的 mutate
rowSums
to add a column with the row sums of X1-X3mutate
across
all X
andcoalesce
each X
with rowSum1
rowSum1
column is gone away because not needed ->.keep="unused"
argument of mutate
library(tidyverse)
df %>%
mutate(rowsum1 = rowSums(select(., starts_with("X")), na.rm=TRUE)) %>%
mutate(across(starts_with("X"), ~coalesce(.,rowsum1)),.keep="unused")
输出:
ID X1 X2 X3
<chr> <dbl> <dbl> <dbl>
1 A 0.96 1.93 0.97
2 B 1 2.01 1.01
3 C 0.98 0.03 1.01
4 A 1 2 1
5 D 1.04 0.05 0.99