且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用dplyr有条件地将列中的值替换为另一列中的值

更新时间:2021-08-21 23:41:27

您可以使用 mutate_at ifelse

df %>% mutate_at(vars(starts_with('sample')), funs(ifelse(. == 1, a, .)))

# A tibble: 3 x 3
#      a sample1 sample2
#  <dbl>   <dbl>   <dbl>
#1   0.1     0.0     0.1
#2   0.2     0.2     0.2
#3   0.3     0.3     0.0

vars(starts_with('sample'))匹配以 sample mutate_at 将函数 funs(ifelse(。== 1,a,。))应用于每一列; 代表此处的匹配列。

vars(starts_with('sample')) matches all columns that starts with sample and mutate_at applies the function funs(ifelse(. == 1, a, .)) to each column; . stands for the matched column here.

如果确保所有示例列仅包含 1 0 ,可以将其缩短为:

If you are sure all the samples columns contain only 1 and 0, it can be shortened as:

df %>% mutate_at(vars(starts_with('sample')), funs(. * a))

# A tibble: 3 x 3
#      a sample1 sample2
#  <dbl>   <dbl>   <dbl>
#1   0.1     0.0     0.1
#2   0.2     0.2     0.2
#3   0.3     0.3     0.0