Merge data frames

Asked

Viewed 2,388 times

6

I have two data frame (see below) with information on consumption and gain of animals. Consumption was collected each day and gain in larger intervals. I want to join one next to the other, having a column of Animal, Day, Consumption and Gain. In this case, in gain, where there is no information, keep as NA. How can I do that?

DfConsumo
Animal	Dia	Consumo
5	2	1959.44
5	4	2015.125
5	5	2062.513
5	6	2102.862
5	7	2157.486
5	8	2213.519
5	9	2279.803
5	10	2317.222
5	11	2428.641
6	3	2000
6	4	2041.661
6	5	2049.473
6	6	2111.409
6	7	2149.92
6	8	2153.251
6	9	2207.271
6	10	2246.633
6	11	2297.115

DfGanho
Animal	Dia	Ganho
5	2	0.95
5	9	0.95
6	3	0.95
6	9	0.96

1 answer

6

The function merge with the option all = T solves your problem. See code below:

DfConsumo <- data.frame(
  Animal = c(rep(5,9), rep(6,9)),
  Dia = c(2,4,5,6,7,8,9,10,11,3,4,5,6,7,8,9,10,11),
  Consumo = c(1959.44,2015.125,2062.513,2102.862,2157.486,2213.519,2279.803,2317.222,2428.641,
          2000,2041.661,2049.473,2111.409,2149.92,2153.251,2207.271,2246.633,2297.115)
)
DfGanho = data.frame(Animal = c(5,5,6,6), Dia = c(2,9,3,9), Ganho = c(.95,.95,.95,.96))

Df <- merge(DfConsumo, DfGanho, all = T)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.