jonestats
jonestats

Reputation: 349

Tabulating variables based on conditions

I have this data and I want to tabulate the columns on conditions based on q8_12:

q8_12   q8_13_1 q8_13_2 q8_13_3 q8_13_4 q8_13_5
YES NO  NO  NO  NO  NO
YES NO  NO  NO  YES NO
NO  NO  NO  NO  NO  NO
NO  NO  NO  NO  NO  NO
NO  NO  NO  NO  NO  NO
YES NO  NO  NO  NO  NO
NO  NO  NO  NO  NO  NO
YES NO  NO  NO  NO  NO
YES NO  NO  NO  NO  YES
YES NO  NO  NO  NO  YES
YES NO  NO  NO  NO  YES
YES NO  NO  NO  NO  NO
YES NO  NO  NO  YES NO
NO  NO  NO  NO  NO  NO

I am using the if function:

if(q8_12=='YES') table(q8_13_11)

and I get this error

Warning in if (q8_12 == "YES") table(q8_13_11) :
the condition has length > 1 and only the first element will be used

Anyone has an idea of how to go about this problem?

Upvotes: 0

Views: 875

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

You can use by:

by(dat[-1], dat[1], summary)

where dat is the name of your data frame.

q8_12: NO
 q8_13_1 q8_13_2 q8_13_3 q8_13_4 q8_13_5
 NO:5    NO:5    NO:5    NO :5   NO :5  
                         YES:0   YES:0  
-------------------------------------------------------------------------------- 
q8_12: YES
 q8_13_1 q8_13_2 q8_13_3 q8_13_4 q8_13_5
 NO:9    NO:9    NO:9    NO :7   NO :6  
                         YES:2   YES:3  

Upvotes: 1

Thomas
Thomas

Reputation: 44525

You want to index, not use if:

table(q8_13_11[q8_12=='YES'])

You may also just want a crosstab:

table(q8_13_11, q8_12)

Upvotes: 0

Related Questions