How to change rows of tables in R by values of the same row only of another column [closed]

3
   [,1]            [,2]
[1,] "NAO INFORMADO" "1" 
[2,] "2"             "3"
[3,] "NAO INFORMADO" "5" 
[4,] "4"             "1" 
[5,] "NAO INFORMADO" "3" 
[6,] "6"             "5"

I wanted to change all values not reported by the values in column 2 of the same line

    
asked by anonymous 09.02.2016 / 02:56

1 answer

4

Your data has a very strange format because it is an array with text and numbers. Probably the ideal would be to replace the NAO INFORMADO with NA , when reading the values. In the current way, you can do the following:

dados <- read.table(text="NAO INFORMADO, 1 
2,             3
NAO INFORMADO, 5 
4,             1 
NAO INFORMADO, 3 
6,             5", sep = ",", stringsAsFactors = FALSE)

dados[dados[,1] == "NAO INFORMADO",1] <- dados[dados[,1] == "NAO INFORMADO",2]

dados
#  V1 V2
#1  1  1
#2  2  3
#3  5  5
#4  4  1
#5  3  3
#6  6  5

But if they were NA , it would be a little simpler:

dados[is.na(dados[,1]),1] <- dados[is.na(dados[,1]),2]

Note that this form considers that your data is an array. It would also work if it were a data.frame , but in this case it would be possible to write a slightly more elegant code.

    
09.02.2016 / 22:50