2

I have a vector with 15 values ranging from 1 to 4.

values <- c(1,2,3,1,2,3,1,2,2,2,1,3,1,2,4)

Lets say this is an item in a questionnaire and 15 people got asked a certain question. 1 to 2 means, the respondant is referring to that question with a "No", while the values 3 or 4 indiciate a positive response to that question. I only want to find out the percentage of those who gave a positive answer, hence the amount of respondants who answedred with a 3 or 4, divided by the total amount of all participants.

I started with table() and prop.table():

round(prop.table(table(values)), 2) which yields to

   1    2    3    4 
0.33 0.40 0.20 0.07 

Is there a way to use prop.table so that it gives me the percentage of those who indicated a 3 OR a 4 (and only those). Should I dichotomize the values first?

The result should look something like this:

values
0.27
Sascha
  • 159
  • 6

2 Answers2

1

One option that avoids modifying or creating new data is to use prop.table after creating a logic table with %in%:

prop.table(table(values %in% c(3,4)))

# or 
# proportions(table(values %in% c(3,4))) # Thanks @GKi

#    FALSE      TRUE 
#0.7333333 0.2666667 

The line values %in% c(3,4) creates a Boolean vector the same length as the data values. table and prop.table then summarize it. Since R mathematically interprets TRUE/FALSE as 1/0, respectively, it will return the proportion.

If you only wanted the single proportion instead of both:

prop.table(table(values %in% c(3,4)))["TRUE"] # Thanks @GKi

# or 
# proportions(table(values %in% c(3,4)))["TRUE"] 

#     TRUE 
#0.2666667 
jpsmith
  • 11,023
  • 5
  • 15
  • 36
1

As it is only one class, you can use mean.

mean(values > 2)
#mean(values %in% c(3,4)) #Alternative
#[1] 0.2666667
GKi
  • 37,245
  • 2
  • 26
  • 48