I’ll do it in two lines of code.
Just see that the logical values FALSE/TRUE are coded internally by R as integers 0/1, respectively. Then, it is first seen that the values of the two columns are equal and then become integers.
It is still necessary to see if the columns are class "character" or "factor". The functions read.table and derivatives assume the argument
stringsAsFactors = TRUE
and therefore, to avoid surprises, the columns are compared as "character". Another solution will be to read the data with the above argument with the value FALSE.
dados$CHECK <- as.character(dados$ORIENTAÇÃO) == as.character(dados$VOTO)
dados$CHECK <- as.integer(dados$CHECK)
dados
# ORIENTAÇÃO VOTO CHECK
#1 Sim Sim 1
#2 Não Sim 0
#3 Sim Não 0
#4 Não Não 1
#5 Sim Abstenção 0
Another option is to use the package dplyr, very popular to transform data.
library(dplyr)
dados %>%
mutate(ORIENTAÇÃO = as.character(ORIENTAÇÃO),
VOTO = as.character(VOTO),
CHECK = as.integer(ORIENTAÇÃO == VOTO))
The result is the same.
Editing.
Yet another solution.
dados$CHECK <- as.integer(Map(`==`, dados[[1]], dados[[2]]))
Dice.
I added a data line to not have the same levels of "factor" in both columns, if the base is read as the default value of stringsAsFactors. This is the first case below.
first case: Read as "factor".
dados <- read.table(text = "
ORIENTAÇÃO VOTO
Sim Sim
Não Sim
Sim Não
Não Não
Sim Abstenção
", header = TRUE)
second case: Read as "character".
dados <- read.table(text = "
ORIENTAÇÃO VOTO
Sim Sim
Não Sim
Sim Não
Não Não
Sim Abstenção
", header = TRUE, stringsAsFactors = FALSE)
Perfect, Rui. Thank you very much. It worked well! Strong hug!
– Guilherme Marques