简体   繁体   中英

Changing values in a data.frame based upon another data.frame

Below is a hypothetical example of what I'm trying to accomplish:

   a  b         A  B
1  3  5      1  2  4
2  7  9      2  6  8

I have two data.frames of equal size. Based on each value in the first data.frame , I want to update the corresponding value in the second frame. If I was to write this using a C-style for loop with a hypothetical condition it would look like this:

for (i = 0; i < numRol; i++) {
    for (j = 0; j < numCol; j++) {
        if (frame1[i][j] < frame2[i][j])
            frame2[i][j] += 1
        else
            frame2[i][j] -= 1
    }
}

So in this example the second data.frame would be transformed to this:

   A  B
1  1  3
2  5  7

In this case of R, I don't think I'd need to use a for loop, but instead could use some variation of the apply family.

For my specific case if I find a 0 in frame1, I'd like to put a 1 in the same spot in frame2. In this case, I would probably need to use a nested apply, but I'm not quite sure how to write a generic reproducible example.

If your data.frames are stored as df1 and df2 , eg:

 df1 = data.frame(a=c(3,7), b=c(5,9))
 df2 = data.frame(a=c(2,6), b=c(4,8))

Then you can just compare the whole structures. So what you're asking could be accomplished with something like:

df2[df1 == 0] <- 1
df2[df1 < df2] = df2[df1 < df2] + 1
df2[df1 > df2] = df2[df1 > df2] - 1

Depending on how you want to handle the zero case

To add or subtract 1 based on df1 < df2, you could use

df2 + ((2 * (df1 < df2)) - 1)
  A B
1 1 3
2 5 7

Here

((2 * (df1 < df2)) - 1)

returns

      a  b
[1,] -1 -1
[2,] -1 -1

and the opposite comparison returns

((2 * (df1 > df2)) - 1)
     a b
[1,] 1 1
[2,] 1 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM