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

Asked

Viewed 2,018 times

1

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

inserir a descrição da imagem aqui]

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

  • 1

    You must have some NA in its vector, make sum(is.na(rehab.1$IAM1)) to confirm that everything is all right. Another thing you need to fix is that before prop.table() you need to use table() then it would be prop.table(table(rehab.1$IAM1))

  • I didn’t really understand the question, turning a numeric variable into a string can be done with as.character(). You can better illustrate his doubt?

  • Thanks Andrelrms, I was wrong the way I used the prop.table() function, I really missed using the table. I imagined this was happening because I was supposed to turn 0 into NO and 1 into YES, but I see it has nothing to do with it. I started studying R now and I’m still getting hit with these basic things. Thanks, big hug!

1 answer

1

I would suggest closing the question, but how can it be useful for other users I will put here two useful knowledge that would solve the problem and present an important concept about the use of 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 zeros and ones just use the table command:

table(vetor)

resulting

 0  1 
 9 11

So when using Prob.table() in this 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 "YES" and "NO". In this case the ideal is to convert the variable into factor (factor).

vetor <- factor(vetor)

such that now the factor has two levels: "0" and "1". Note that now are no more numbers, but levels of a 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" just change the name of the levels to "YES" and "NO" in the order in which they are presented.

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() commands will work as before.

Browser other questions tagged

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