首页 > 解决方案 > 根据相邻列的值替换多列中的值

问题描述

    # Create a data frame
        > df <- data.frame(a = rnorm(7), b = rnorm(7), c = rnorm(7), threshold = rnorm(7))
        > df <- round(abs(df), 2)
        > 
        > df
             a    b    c threshold
        1 1.17 0.27 1.26      0.19
        2 1.41 1.57 1.23      0.97
        3 0.16 0.11 0.35      1.34
        4 0.03 0.04 0.10      1.50
        5 0.23 1.10 2.68      0.45
        6 0.99 1.36 0.17      0.30
        7 0.28 0.68 1.22      0.56
        > 
        >
    # Replace values in columns a, b, and c with NA if > value in threshold
        > df[1:3][df[1:3] > df[4]] <- "NA"
        Error in Ops.data.frame(df[1:3], df[4]) : 
          ‘&gt;’ only defined for equally-sized data frames

可能有一些我无法产生的明显解决方案。目的是如果值大于“阈值”中的值,则将“a”、“b”和“c”列中的值替换为 NA。我需要逐行进行。

如果我做得对,df 将如下所示:

         a    b    c threshold
    1   NA   NA   NA      0.19
    2   NA   NA   NA      0.97
    3 0.16 0.11 0.35      1.34
    4 0.03 0.04 0.10      1.50
    5 0.23   NA   NA      0.45
    6   NA   NA 0.17      0.30
    7 0.28   NA   NA      0.56

我也尝试过 apply() 方法,但无济于事。请问可以帮忙吗??

标签: rdataframereplace

解决方案


您应该dplyr在大多数此类用例中使用。下面的一种方法:

> set.seed(10)
> df <- data.frame(a = rnorm(7), b = rnorm(7), c = rnorm(7), threshold = rnorm(7))
> df <- round(abs(df), 2)
> df
     a    b    c threshold
1 0.02 0.36 0.74      2.19
2 0.18 1.63 0.09      0.67
3 1.37 0.26 0.95      2.12
4 0.60 1.10 0.20      1.27
5 0.29 0.76 0.93      0.37
6 0.39 0.24 0.48      0.69
7 1.21 0.99 0.60      0.87
> 
> df %>%
+   mutate_at(vars(a:c), ~ifelse(.x > df$threshold, NA, .x))
     a    b    c threshold
1 0.02 0.36 0.74      2.19
2 0.18   NA 0.09      0.67
3 1.37 0.26 0.95      2.12
4 0.60 1.10 0.20      1.27
5 0.29   NA   NA      0.37
6 0.39 0.24 0.48      0.69
7   NA   NA 0.60      0.87

推荐阅读