代码之家  ›  专栏  ›  技术社区  ›  ah bon

使用0或NAs替换所选列的负值(使用R)

  •  0
  • ah bon  · 技术社区  · 2 年前

    对于示例数据 df ,我想替换第一列中的负值( x1 )与 0 和第三列( x3 )与 NA 按功能 replace_negatives 详情如下:

    df  <- data.frame(x1 = -3:1,      
                        x2 = -1,
                        x3 = -2:2)
    df 
    

    出:

      x1 x2 x3
    1 -3 -1 -2
    2 -2 -1 -1
    3 -1 -1  0
    4  0 -1  1
    5  1 -1  2
    

    请注意,我不按列名编制索引,因为实际数据中有许多列,而且列名不是固定的。

    replace_negatives <- function(data){
      df <<- data %>% 
        mutate(.[[1]] = if_else(.[[2]] < 0, 0, .[[1]])) %>%
        mutate(.[[3]] = if_else(.[[3]] < 0, NA, .[[3]])) 
      return(df)
    }
    
    lapply(df, replace_negatives)
    

    但它引发了一个错误:

    > replace_negatives <- function(data){
    +   df <<- data %>% 
    +     mutate(.[[1]] = if_else(.[[2]] < 0, 0, .[[1]])) %>%
    Error: unexpected '=' in:
    "  df <<- data %>% 
        mutate(.[[1]] ="
    >     mutate(.[[3]] = if_else(.[[3]] < 0, NA, .[[3]])) 
    Error: unexpected '=' in "    mutate(.[[3]] ="
    >   return(df)
    Error: no function to return from, jumping to top level
    > }
    Error: unexpected '}' in "}"
    

    任何帮助都将受到感谢。

    预期产出:

      x1 x2 x3
    1  0 -1 NA
    2  0 -1 NA
    3  0 -1  0
    4  0 -1  1
    5  1 -1  2
    
    2 回复  |  直到 2 年前
        1
  •  1
  •   AndrewGB    2 年前

    你可以用 across 在函数中:

    library(tidyverse)
    
    replace_negatives <- function(data){
      df <- data %>%
        mutate(across(1, ~ ifelse(. < 0, 0, .)),
               across(3, ~ ifelse(. < 0, NA, .)))
      return(df)
    }
    
    replace_negatives(df)
    

    输出

      x1 x2 x3
    1  0 -1 NA
    2  0 -1 NA
    3  0 -1  0
    4  0 -1  1
    5  1 -1  2
    
        2
  •  1
  •   benson23    2 年前

    要执行所需的操作,这里有一个基本的R方法:

    df  <- data.frame(x1 = -3:1,      
                      x2 = -1,
                      x3 = -2:2)
    
    df[[1]] <- ifelse(df[[1]] < 0, 0, df[[1]])
    df[[3]] <- ifelse(df[[3]] < 0, NA, df[[3]])
    
    df
    #>   x1 x2 x3
    #> 1  0 -1 NA
    #> 2  0 -1 NA
    #> 3  0 -1  0
    #> 4  0 -1  1
    #> 5  1 -1  2
    

    于2022年4月18日由 reprex package (v2.0.1)

        3
  •  0
  •   TarJae    2 年前

    以下是函数的基本R版本:

    replace_negatives <- function(df){
        is.na(df[,1]) <- df[,1] < 0
        index <- df[,3] < 0
        df[,3][index] <- 0
      return(df)
    }
    
    
    replace_negatives(df)
    
      x1 x2 x3
    1 NA -1  0
    2 NA -1  0
    3 NA -1  0
    4  0 -1  1
    5  1 -1  2