Replace Values from one dataframe to another dataframe of unequal length

Viewed 44

I'm giving the minimal example here for my problem,I need to merge two dataframes by ID image I should replace the class values of dataframe1 with dataframe2, I'm not able to get the result as expected , Thanks for the help in advance.

The dataframe1 is having the structure like this

image class type
img01 car   png
img02 bus   png
img03 bus   jpg
img04 car   bmp

The dataframe2 is as below

image class
img02 car
img03 bus
img04 bus

I want the dataframe as below:
image class type
img01 car   png
img02 car   png
img03 bus   jpg
img04 bus   bmp

1 Answers

Here is a way. Create indices into both data frames, telling where the image id values match. Then assign the class based on those indices.

x <- 'image class type
img01 car   png
img02 bus   png
img03 bus   jpg
img04 car   bmp'
dataframe1 <- read.table(textConnection(x), header = TRUE)
x <- 'image class
img02 car
img03 bus
img04 bus'
dataframe2 <- read.table(textConnection(x), header = TRUE)

i <- match(dataframe2$image, dataframe1$image) |> na.omit()
j <- match(dataframe1$image, dataframe2$image) |> na.omit()
dataframe1$class[i] <- dataframe2$class[j]
dataframe1
#>   image class type
#> 1 img01   car  png
#> 2 img02   car  png
#> 3 img03   bus  jpg
#> 4 img04   bus  bmp

Created on 2022-07-29 by the reprex package (v2.0.1)


A variant of the code above is

common <- intersect(dataframe2$image, dataframe1$image)
i <- match(common, dataframe1$image)
j <- match(common, dataframe2$image)
dataframe1$class[i] <- dataframe2$class[j]

Created on 2022-07-29 by the reprex package (v2.0.1)

Related