简体   繁体   中英

Replace Dataframe column with another dataframe based on conditions - R

i'm with some trouble and maybe someone here can help me!

I´ve a dataframe with three columns( ID1, ID2 and VALUE1). Also i've another dataframe that follows the same configuration but with another values for some ID1 and ID2. I'm trying to replace the values on VALUE1 column in dataframe1 with values that are in the column VALUE1 in dataframe2 only based on multiple conditions. This means, when ID1 and ID2 meet some conditions "x" and "y", then replace those values from dataframe 2.

Below i attach an example. The idea is to use df1 and when ID1=5 and ID2<100, then replace values of VALUE1, from df2. The df3 is the expected outcome( Note that i want to keep all the columns from the df1, just replacing the values when conditions meet)

Example:

df1 <- data.frame(ID1=c(1,2,3,4,5,5,5,4,3,5), 
                    ID2 = c(10,20,30,40,50,150,200,99,10,25), 
                    VALUE1 = c(100,200,300,400,200, 100,200,40,150,70),
                    NAME = c("Juan", "Rodrigo","Pedro","Lucas","d", "e","f","g","x","a"),
                    SURNAME = c("perez","jones","bla","lopez","martinez","rodriguez","jerez","dieguez","gimenez","mendez"))
     
df2 <- data.frame(ID1=c(5,5,5,5), 
                    ID2 = c(50,150,200,25), 
                    VALUE1 = c(40,30,180,200))
                    
df3 <- data.frame(ID1=c(1,2,3,4,5,5,5,4,3,5), 
                    ID2 = c(10,20,30,40,50,150,200,99,10,25), 
                    VALUE1 = c(100,200,300,400,50, 100,200,40,150,200),
                    NAME = c("Juan", "Rodrigo","Pedro","Lucas","d", "e","f","g","x","a"),
                    SURNAME = c("perez","jones","bla","lopez","martinez","rodriguez","jerez","dieguez","gimenez","mendez"))

Example as image

I tried some things like merge, if, ifelse but i did not reach the outcome. I'm wondering if someone can help me!

Thanks in advance!

I think you can use the following solution:

library(dplyr)

df1 %>%
  left_join(df2, by = c("ID1", "ID2")) %>%
  mutate(VALUE1.x = ifelse(ID1 == 5 & ID2 < 100, VALUE1.y, VALUE1.x)) %>%
  select(-VALUE1.y) %>%
  rename_with(~ sub("\\.x", "", .), contains(".x")) 

   ID1 ID2 VALUE1    NAME   SURNAME
1    1  10    100    Juan     perez
2    2  20    200 Rodrigo     jones
3    3  30    300   Pedro       bla
4    4  40    400   Lucas     lopez
5    5  50     40       d  martinez
6    5 150    100       e rodriguez
7    5 200    200       f     jerez
8    4  99     40       g   dieguez
9    3  10    150       x   gimenez
10   5  25    200       a    mendez

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