Search code examples
rdataframerowassignsequential

assign values from same row in R


I want to assign the row value of B to row A only when A = 1. This is what I have done so far:

Data frame:

df <- data.frame('A' = c(1,1,2,5,4,3,1,2), 'B' = c(100,200,200,200,100,200,100,200))


        A     B
    1   1     100
    2   1     200
    3   2     200
    4   5     200
    5   4     100
    6   3     200
    7   1     100
    8   2     200

Output:

df$A[df$A == 1] <- df$B

        A     B
    1   100   100
    2   200   200
    3   2     200
    4   5     200
    5   4     100
    6   3     200
    7   200   100
    8   2     200

As you can see, rows 1 and 2 do what they are supposed to do. However, row 7 doesn't, but instead takes the value from row 3 - it is assigning values sequentially.

My question: how do I assign values that takes the inputs from the same row?


Solution

  • Use:

    df$A[df$A == 1] <- df$B[df$A == 1]
    

    You need to apply the same index to both, column to be replaced and column that holds the replacements.