0

I want to merge two imported dataset with different lengths and keep the values from B if both datasets has values. Dataset A has daily data from 1970 to 2016, dataset B has daily data from 1980 to 2016. The combined dataset should be the same length as A, but with values from B stuffed into it. Example data:

a=matrix(c(1:10),10,10) b=matrix(c(NA,NA,3:8,NA,NA),10,5)

NielsJo
  • 45
  • 5
  • http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – JanLauGe Apr 05 '17 at 12:44
  • Possible duplicate of [Counting the result of a left join using dplyr](http://stackoverflow.com/questions/33535633/counting-the-result-of-a-left-join-using-dplyr) – JanLauGe Apr 05 '17 at 12:46
  • 2
    Those are matrices, not data.frames. Also, they have the same values in the same rows, when b is not NA. At a minimum, please revise your data to include your desired output. Note that you can turn matrices into data.frames by wrapping them in the `data.frame` function. `a <- data.frame(matrix(...))`. – lmo Apr 05 '17 at 13:53

1 Answers1

1

You can join the two data frames together and then create a new column based on whatever rules you want. I don't know exactly what your data look like, but a left_join will get you the number of rows in dataset a, and then you can mutate a new column to fill in the blanks. Finally you discard the extra two columns with select.

library(tidyverse)

a <- tibble(year = 1970:2016, value = rnorm(47))

b <- tibble(year = 1980:2016, value = rnorm(37))

a %>%
  left_join(b, by = "year") %>%
  mutate(value = ifelse(is.na(value.y), value.x, value.y)) %>%
  select(year, value)
Andrew Brēza
  • 7,705
  • 3
  • 34
  • 40