How to change table rows in R by values from the same row only from another column

Asked

Viewed 1,327 times

3

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

wanted to change all values not informed by the values in column 2 of the same row

  • 1

    Hello, Leonardo. Welcome to Stack Overflow. Your question is not clear enough. Please edit it with examples of expected inputs and outputs.

1 answer

4

Your data has a very strange format, as it is an array with text and numbers. Probably the ideal would be to replace the NAO INFORMADO for NA, in reading the values. In the current form, 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, 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 code a little more elegant.

Browser other questions tagged

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