Home > Mobile >  How to make R take values from another column?
How to make R take values from another column?

Time:04-15

I have two tables with data in R. What I want is to inherit values from the v2 column of Table 1 to the v2 column of Table 2 with the same ID (v1 column in both tables) and if the value in the v2 column of table2 is 0.

The columns in the tables look like this:

Table 1

v1 v2
11 1
22 1
33 0
44 1
55 1

Table 2

v1 v2
11 2
22 3
33 7
44 7
55 0
66 0

What I am expecting for results

v1 v2
11 2
22 3
33 7
44 7
55 1
66 0

Does anyone know how I could manage this?

Thanks in advance!

CodePudding user response:

You could do left_join:

library(dplyr)

table2 %>% 
  left_join(table1, by = "v1") %>% 
  mutate(v2 = ifelse(v2.x == 0, v2.y, v2.x),
         .keep = "unused")

This returns

# A tibble: 6 x 2
     v1    v2
  <dbl> <dbl>
1    11     2
2    22     3
3    33     5
4    44     7
5    55     1
6    66    NA

Note: There is no value for 66 in table1.

Depending on the real structure of your tables, a full_join might be an option.

CodePudding user response:

An option with data.table

library(data.table)
setDT(df2)[df1, v2 := fifelse(v2 == 0, i.v2, v2), on = .(v1)]

-output

> df2
      v1    v2
   <int> <int>
1:    11     2
2:    22     3
3:    33     5
4:    44     7
5:    55     1
6:    66     0
  •  Tags:  
  • r
  • Related