Replacing occurrences of a number in multiple columns of data frame with another value in R

后端 未结 4 658
-上瘾入骨i
-上瘾入骨i 2020-12-03 03:09

ETA: the point of the below, by the way, is to not have to iterate through my entire set of column vectors, just in case that was a proposed solution (just

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 03:28

    Just to provide a different answer, I thought I would write up a vector-math approach:

    You can create a transformation matrix (really a data frame here, but will work the same), using a the vectorized 'ifelse' statement and multiply the transformation matrix and your original data, like so:

    df.Rep <- function(.data_Frame, .search_Columns, .search_Value, .sub_Value){
       .data_Frame[, .search_Columns] <- ifelse(.data_Frame[, .search_Columns]==.search_Value,.sub_Value/.search_Value,1) * .data_Frame[, .search_Columns]
        return(.data_Frame)
    }
    

    To replace all values 4 with 10 in the data frame 'data' in columns 2 through 3, you would use the function like so:

    # Either of these will work.  I'm just showing options.
    df.Rep(data, 2:3, 4, 10)
    df.Rep(data, c("var1","var2"), 4, 10)
    
    #   name var1 var2
    # 1    a    1    3
    # 2    a    2    3
    # 3    a    3    3
    # 4    b   10   10
    # 5    b    5   10
    # 6    b    6   10
    # 7    c    7    5
    # 8    c    8    5
    # 9    c    9    5
    

提交回复
热议问题