更新时间: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