Search code examples
rdataframecomparecell

Can i exchange two different cell data in R?


i got two dataframes in R. And i want to compare two dataframe and change the cell data.

data1
a
b
data11 data21
c 1
a 2

if i compare [data1] and [data11], if "a" is exist in range [data11], then i change the "a" to "2" which is same row in data21.


Solution

  • I'm assuming you are working with two dataframes:

    df1 <- data.frame(col1 = c("a", "b"))
    df1
    #>   col1
    #> 1    a
    #> 2    b
    
    df2 <- data.frame(data11 = c("c", "a"), data21 = c(1, 2))
    df2
    #>   data11 data21
    #> 1      c      1
    #> 2      a      2
    

    If you use ifelse(), the indexing might be incorrect (we would expect the results to be "2" "b" here):

    ifelse(df1$col1 %in% df2$data11, df2$data21, df1$col1)
    #> [1] "1" "b"
    

    So you can use merge() instead:

    df3 <- merge(df1, df2, by.x = "col1", by.y = "data11", all.x = TRUE)
    df3$data21 <- ifelse(is.na(df3$data21), df3$col1, df3$data21)
    df3
    #>   col1 data21
    #> 1    a      2
    #> 2    b      b