How to transform numeric variables into strings in R (0 = NO and 1 = YES)?

1

1 I have a data sheet where 0 = No and 1 = Yes. When I try to create a table of this variable the following appears:

]

How do I make the function prop.table to the pie function of the pizza chart recognize these variables as YES and NO?

    
asked by anonymous 22.03.2016 / 01:01

1 answer

1

I would suggest closing the question, but as it may be something useful to other users I will put here two useful knowledge that would solve the problem and present an important concept about using R.

Initially I will generate a reproducible example of a vector of zeros and ones with 20 numbers.

set.seed(1)
vetor <- rbinom(n = 20, prob = 0.5, size = 1)

To count the zeros and ones, simply use the command table:

table(vetor)

That results

 0  1 
 9 11

So when using prob.table () on that result:

prop.table(table(vetor))

we get

0    1 
0.45 0.55

So far, they are all numbers. Let's say you want the results to be exactly like "YES" and "NO". In this case the ideal is to convert the variable into factor.

vetor <- factor(vetor)

such that now the factor has two levels: "0" and "1". See that they are no longer numbers, but levels of one factor. You can get the levels of a factor through the levels () command.

levels(vetor)

result in

[1] "0" "1"

To leave as "YES" and "NO" simply change the name of the levels to "YES" and "NO" in the order in which they appear.

levels(vetor) <- c("NÃO", "SIM")

such that now zero is no and one is yes.

print(vetor)

[1] NÃO NÃO SIM SIM NÃO SIM SIM SIM SIM NÃO NÃO NÃO SIM NÃO SIM NÃO
[17] SIM SIM NÃO SIM
Levels: NÃO SIM

The table () and prop.table () command will work as before.

    
10.09.2016 / 21:51