Replace NA with data from another column

2

I would like to replace NA with the contents of another column. I have the following data:

NOME    TIPO        VALOR
ABC     INTERNACAO  10
ADD                 20
AFF     CONSULTA    30
DDD     EXAME       40
RTF                 50
DRGG    EXAME       60

How would you replace NA with the contents of the next column? Example: The NA of the line ADD (column TIPO ) would be replaced by the number 20. And in the line RTF (column TIPO ) would be replaced by 50. Thank you

    
asked by anonymous 31.08.2018 / 14:00

1 answer

4

When creating your example, the variable TIPO comes as factor . I had to convert it to character to assign a number to the empty position.

dados <- data.frame(NOME = c("ABC", "ADD", "AFF", "DDD", "RTF", "DRGG"),
                TIPO = c("INTERNACAO", "", "CONSULTA", "EXAME", "", "EXAME"),
                VALOR = c(10, 20, 30, 40, 50, 60))
dados$TIPO <- as.character(dados$TIPO)
pos <- which(dados$TIPO == "")
dados$TIPO[pos] <- dados$VALOR[pos]
    
31.08.2018 / 14:47