Replace NA with data from another column

Asked

Viewed 126 times

2

I would like to replace NA by the content 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 the NA by the content of the next column? Example: O NA of the line ADD (spine TIPO), would be replaced by number 20. And on the line RTF (spine TIPO) would be replaced by 50. Grateful

1 answer

4


When creating your example, the variable TIPO comes as factor. I had to turn her into character to assign a number in 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]
  • the example you used is empty. How would you do if the data were in NA?

  • replace the line with the command which for pos <- which(is.na(dados$TIPO))

Browser other questions tagged

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