danni.j.t
danni.j.t

Reputation: 15

Fill NA values in data frame from another data frame will preserving existing values

I have tried merge and think I am doing something wrong because it the existing values get dropped. Here is an example :

Data frame 1: 
ID  Color  Size       Shape 
1   red      s        circle
2   NA       s        circle
3   blue     s        circle
4   NA       s        circle

Data frame 2: 
ID   Color 
2    blue
4    green 

I want this...

ID  COLOR       Size       Shape
1   red           s       circle 
2   blue          s       circle
3   blue          s       circle
4   green         s       circle 

Here Is a sample of my actual data frames.

enter image description here

enter image description here

I tried this....

Dataframe1 <- scalemerge
Dataframe2 <- finding_NA_URIS
colnames(finding_NA_URIS) <- c("track","artist_uri","track_uri","album")
 inx <- is.na(Dataframe1$track_uri)
Dataframe1$track_uri[inx] <- Dataframe2$track_uri[match(Dataframe1$track[inx], Dataframe2$track)]

Upvotes: 0

Views: 25

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

With base R you can use match.

inx <- is.na(Dataframe1$Color)
Dataframe1$Color[inx] <- Dataframe2$Color[match(Dataframe1$ID[inx], Dataframe2$ID)]

Dataframe1
#  ID Color Size  Shape
#1  1   red    s circle
#2  2  blue    s circle
#3  3  blue    s circle
#4  4 green    s circle

DATA.

Dataframe1 <- read.table(text = "
ID  Color  Size       Shape 
1   red      s        circle
2   NA       s        circle
3   blue     s        circle
4   NA       s        circle
", header = TRUE, stringsAsFactors = FALSE)


Dataframe2 <- read.table(text = "
ID   Color 
2    blue
4    green
", header = TRUE, stringsAsFactors = FALSE)

Upvotes: 1

Related Questions