【问题标题】:Conditionally replace the values in columns to value in another column using dplyr使用 dplyr 有条件地将列中的值替换为另一列中的值
【发布时间】:2017-10-20 14:50:16
【问题描述】:

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

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

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 个样本列)都这样做,因此循环列的方法会更好(尽管我知道循环是魔鬼)。

感谢您的帮助!

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    您可以将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
    

    【讨论】:

    • 伙计...我尝试使用 mutate_at 玩了一段时间,但我的错误是使用 replace() 而不是 ifelse()。这工作得很好......谢谢!
    • replace 也是我的第一个想法。但是要求condition和replacement长度一致或者可回收,不如这里ifelse方便。
    【解决方案2】:

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

    > 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
    

    【讨论】:

      猜你喜欢
      • 2018-10-18
      • 2016-06-07
      • 2021-07-02
      • 2020-08-13
      • 2012-11-06
      • 2019-12-04
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多