Fill cells with NA by an annual logical sequence in R

0

I have a dataframe with 25 people and their respective ages from 2012 to 2015, but in a few years the ages have not been filled.

id<-c(1:25)
idade_2012<-c(21, 18, 19, 25, 20, 12, 12, 13, 14, 29, 40, 11, 15, 14, 24, 16, 14, 12, 13, 14, 12, 21, 14, 16, 13)
idade_2013<-c(22, NA, 20, NA, NA, 13, 13, 14, 15, 30, 41, 12, 16, 15, 25, NA, 15, 13, 14, 15, 13, 22, 15, NA, NA)
idade_2014<-c(NA, NA, NA, NA, NA, NA, 14, 15, 16, 31, NA, 13, 17, 16, 26, 18, NA, 14, 15, NA, 14, 23, 16, NA, NA)
idade_2015<-c(NA, NA, NA, 28, NA, 15, 15, 16, 17, NA, NA, 14, NA, 17, 27, 19, NA, 15, 16, NA, NA, 24, 17, NA, 16)

df<-data.frame(id, idade_2012, idade_2013, idade_2014, idade_2015)
df

df

I'dliketogetasaresultawholedffilledwiththelogicalsequenceofage,asperthepicture.

    
asked by anonymous 05.04.2018 / 19:46

1 answer

2

I do not understand what you mean by this, but it seems like all the information you need is in idade_2012

To fill in the other columns just do

id<-c(1:25)
idade_2012 <- c(21, 18, 19, 25, 20, 12, 12, 13, 14, 29, 40, 11, 15, 14, 24, 16, 14, 12, 13, 14, 12, 21, 14, 16, 13)
idade_2013 <- idade_2012 + 1
idade_2014 <- idade_2012 + 2
idade_2015 <- idade_2012 + 3

df<-data.frame(id, idade_2012, idade_2013, idade_2014, idade_2015)
df

For a more general case you can get the year of birth of each id with the library dplyr

library(dplyr)
df %>% 
   gather(idade_ano, idade, -id) %>% 
   filter(!is.na(idade)) %>% 
   separate(idade_ano, c("prefix", "ano"), sep = "_") %>% 
   mutate(ano = as.integer(ano)) %>% 
   mutate(nascimento = ano - idade) %>%
   select(id, nascimento) %>%
   distinct()

You should consider deleting the columns of ages and stay with the year of birth if possible.

    
05.04.2018 / 19:56