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

Conditionally replace the values in columns to value in another column using dplyr

我非常努力地寻找这个问题的答案,如果重复,我深表歉意。

我会制作一些虚拟数据来解释我的问题。

tibble(a=c(0.1, 0.2, 0.3), sample1 = c(0, 1, 1), sample2 = c(1, 1, 0))

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

如何有条件地更改 sample1sample2 列中的值,以便如果它们等于 1,则它们将采用a.

的值

生成的小标题应如下所示:

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

理想情况下,我不想为每个单独的样本列(我有 >100 个样本列)执行此操作,因此循环遍历列的方法会更好(尽管我知道循环是魔鬼)。

感谢您的帮助!

您可以将 mutate_atifelse 一起使用:

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, .)) 应用于每一列; .代表此处匹配的列。


如果您确定所有示例列仅包含 10,则可以将其缩短为:

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

非 dplyr 解决方案使用 which():

> t=tibble(a=c(0.1, 0.2, 0.3), sample1 = c(0, 1, 1), sample2 = c(1, 1, 0))

> whichRows=which(t$sample1==t$sample2)

> t[whichRows,c('sample1','sample2')]<-t[whichRows,'a']

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