0

I have

dat1<- read.table (text='Prey, spec, offer AAA, 77, PRML AAB, 2, PMRT AAC, 8, TBKB AAD, 90, MYO9', header =T, sep =',')

> dat1
  Prey spec offer
1  AAA   77  PRML
2  AAB    2  PMRT
3  AAC    8  TBKB
4  AAD   90  MYO9

I have another data frame with missing values, wan to fill the missing values from previous data frame

dat2<- read.table (text='Prey, spec, offer AAB, NA, PMRT AAC, 8, TBKB AAD, NA, MYO9', header =T, sep =',')

> dat2
  Prey spec offer
1  AAB   NA  PMRT
2  AAC    8  TBKB
3  AAD   NA  MYO9

my desired output

 Prey spec offer
1  AAB    2  PMRT
2  AAC    8  TBKB
3  AAD   90  MYO9
zx8754
  • 52,746
  • 12
  • 114
  • 209
Jay
  • 67
  • 8
  • Your `dat1` and `dat2` objects do not load as data frames with your existing code. Please have a read of http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example and consider using `dput()`. You should be able to subset with `is.na()` and a reproducible example means we can demonstrate the technique with your data – Phil Aug 17 '16 at 09:57
  • AAB should be 2 based on the input you showed. Try with `dat1$spec[match(dat2$Prey, dat1$Prey)]` – akrun Aug 17 '16 at 10:04
  • @RonakShah No, it is not a dupe of that link – akrun Aug 17 '16 at 10:24

1 Answers1

1

We can use match with is.na

i1 <- is.na(dat2$spec)
dat2$spec[i1] <- dat1$spec[match(dat2$Prey[i1], dat1$Prey)]
dat2
#  Prey spec offer
#1  AAB    2  PMRT
#2  AAC    8  TBKB
#3  AAD   90  MYO9

data

dat1 <- structure(list(Prey = c("AAA", "AAB", "AAC", "AAD"), spec = c(77L, 
2L, 8L, 90L), offer = c("PRML", "PMRT", "TBKB", "MYO9")), .Names = c("Prey", 
"spec", "offer"), class = "data.frame", row.names = c("1", "2", 
"3", "4"))

dat2 <- structure(list(Prey = c("AAB", "AAC", "AAD"), spec = c(NA, 8L, 
NA), offer = c("PMRT", "TBKB", "MYO9")), .Names = c("Prey", "spec", 
"offer"), class = "data.frame", row.names = c("1", "2", "3"))
akrun
  • 874,273
  • 37
  • 540
  • 662