| Type: | Package |
| Title: | Data and Functions for "An R Companion to Political Analysis, Fourth Edition" |
| Version: | 1.0.0 |
| Description: | Provides teaching-oriented functions and datasets for "An R Companion to Political Analysis, Fourth Edition" (forthcoming 2026). Functions produce readable tables and graphics for descriptive statistics, data transformation, confidence intervals, hypothesis testing, comparisons, cross-tabulation, and linear and logistic regression. Sampling weights are supported where appropriate, and analysis functions return reusable results for further examination. The package also includes curated political datasets designed for classroom instruction and independent practice. See Edwards and Pollock (forthcoming 2026) https://www.poliscidata.com/textbooks/r_companion_4e.php. |
| License: | CC0 |
| URL: | https://www.poliscidata.com/textbooks/r_companion_4e.php |
| LazyData: | TRUE |
| Encoding: | UTF-8 |
| Depends: | R (≥ 4.0) |
| Imports: | beepr, car, graphics, grDevices, haven, Hmisc, knitr, lmtest, methods, stats, survey, utils |
| Suggests: | hexbin, rgl, scatterplot3d, gdata, testthat (≥ 3.0.0) |
| Config/testthat/edition: | 3 |
| Config/roxygen2/version: | 8.1.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-10-09 13:32:27 UTC; Barry Edwards |
| Author: | Barry C. Edwards |
| Maintainer: | Barry C. Edwards <bce@uga.edu> |
| Repository: | CRAN |
| Date/Publication: | 2026-10-24 08:20:02 UTC |
Confidence interval of a dataset variable's sample mean in table and figure
Description
Reports the confidence interval of a sample mean in table and plot. Default is 95% CI but use can raise or lower confidence level.
Usage
CImean(x, w = NULL, data = NULL, digits = 3, conf = 95,
pop.sd = NULL, printC = FALSE, plot = TRUE, main = NULL,
xlab = NULL, xlim = NULL, table = TRUE, ...)
Arguments
x |
A numeric variable, should be in dataset$var form unless dataset specified in optional data argument. |
w |
(Optional) Sampling weights of variable (optional), must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains x (and w) variable (optional). |
digits |
(Optional) Number of decimal places reported in result (defaults to 3). |
conf |
(Optional) A single number equal to the desired confidence level (i.e. 95, 99, 90, etc.). Default value is 95 percent confidence level. |
pop.sd |
(Optional) A single number equal to the known population standard deviation of x. This value is rarely know, but if it is, critical values for confidence interval are based on standard normal distribution. |
printC |
(Optional) Do you want results printed to .html file in your working directory? Default is FALSE. Set to TRUE to print results. |
plot |
(Optional) Do you want a plot of the confidence interval? Default is TRUE. |
main |
(Optional) Change the main title of plot. Default title generated from conf, x, and w. |
xlab |
(Optional) Label for x-axis of confidence interval plot. |
xlim |
(Optional) Modify x-axis limits of confidence interval plot. |
table |
(Optional) Do you want the confidence interval table reported? (default: TRUE) |
... |
(Optional) additional arguments passed to |
Value
Returns the confidence interval as a vector of numeric values (the lower and upper bounds).
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
RCPA4 Package Tutorial Videos
-
Confidence Intervals for Sample Means with RCPA4's CImean Function 16:16
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 8.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp. 184-186. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Foundations of Inference, Compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
CImean(anes$r_age_election_day)
# using optional w, conf, and data arguments
CImean(x=anes$r_age_election_day, w=anes$wt, conf=90)
CImean(x=r_age_election_day, data=anes, conf=95)
Confidence intervals of a dataset variable's sample proportions in table and figure
Description
Reports the confidence interval of sample proportions in table and plot. Default is 95% CI but use can raise or lower confidence level.
Usage
CIprop(x, w = NULL, data = NULL, digits = 3, conf = 95,
printC = FALSE, plot = TRUE, main = NULL, xlab = NULL, xlim = NULL,
table = TRUE, ...)
Arguments
x |
A nominal or ordinal variable (factor), should be in dataset$var form unless dataset specified in optional data argument. |
w |
(Optional) Sampling weights of variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains x (and w) variable. |
digits |
(Optional) Number of decimal places reported in result (defaults to 3). |
conf |
(Optional) A single number equal to the desired confidence level (i.e. 95, 99, 90, etc.). Default value is 95 percent confidence level. |
printC |
(Optional) Do you want results printed to .html file in your working directory? Default is FALSE. Set to TRUE to print results. |
plot |
(Optional) Do you want a plot of the confidence interval? Default is TRUE. |
main |
(Optional) Change the main title of plot. Default title generated from conf, x, and w. |
xlab |
(Optional) Label for x-axis of confidence interval plot. |
xlim |
(Optional) Modify x-axis limits of confidence interval plot. |
table |
(Optional) Do you want the confidence interval table reported? (default: TRUE) |
... |
(Optional) Additional arguments passed to |
Value
Returns a data frame that gives the lower bound, point estimate, and upper bounds of each value of x variable.
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
RCPA4 Package Tutorial Videos
-
Confidence Intervals for Sample Proportions with RCPA4's CIprop Function 18:29
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 8.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp. 184-186. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Foundations of Inference, Compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
CIprop(anes$life_exprnc_know_smn)
# using optional w and data arguments
CIprop(x=anes$life_exprnc_know_smn, w=anes$wt)
CIprop(x=life_exprnc_know_smn, w=wt, data=anes)
Calculates Cramer's V
Description
Calculates Cramer's V, a measure of association to gauge the strength of the relationship between two nominal-level variables. A score of 0 indicates no relationship; a score of 1 indicates a perfect relationship.
Usage
CramersV(chi, r, c, n)
Arguments
chi |
A number equal to the Chi-Squared statistic |
r |
A number equal to the number of rows |
c |
A number equal to the number of columns |
n |
A number equal to the sample size |
Value
The Cramer's V statistic, a number between 0 and 1.
Examples
library(RCPA4)
CramersV(84.18, 2, 2, 1315)
CramersV(chi=84.18, r=2, c=2, n=1315)
ANES 2024 dataset for R Companion to Political Analysis, Fourth Edition
Description
A student-friendly subset of the 2024 American National Election Study Time Series. Variables were selected and renamed for use in RCPA4 examples. See book Appendix for variable names and descriptions.
Format
A data frame with 5521 rows and 517 variables.
- abort_std_abort_self
Abortion: self-placement
- abortion_scale_self
Position on abortion: self-placement
- addrss_years_lived
Years respondent lived at address
- appr_biden_drop
Approval of Biden dropping from presidential race
- appr_biden_out
Approval of Joe Biden dropping out of presidential race
- appr_cllgs_unvrsts
Approval of how colleges and universities are run
- appr_cong_hndl_its
Approval of Congress handling its job
- appr_dem_new_cand
Approval of Democratic party choosing new candidate
- appr_dvrsty_eqty_dei
Approval of Diversity, Equity, and Inclusion (DEI)
- appr_house_incumbent
Approval of House incumbent
- appr_pres_handle_job
Approval of president handling job
- appr_pres_hndl_abort
Approval of president handling abortion policy
- appr_pres_hndl_crime
Approval of president handling crime
- appr_pres_hndl_econ
Approval of president handling economy
- appr_pres_hndl_frgn
Approval of president handling foreign relations
- appr_pres_hndl_immig
Approve or dissaprove president handling immigration
- appr_pres_immunity
Approval of Supreme Court decision president immune
- appr_prtsts_war_gaza
Approval of protests against war in Gaza
- appr_sup_ct_hndl_its
Approval of Supreme Court handling its job
- appr_trans_ppl_use
Approval of transgender people use bathroom that matches gender identity
- appr_vice_pres_hndl
Approval of vice president handling job
- attn_sxl_hrssmnt_as
Attention to sexual harassment as gone too far/not far enough
- bdgt_tax_favor_opps
Favor or oppose tax on millionaires
- bdgt_tax_imp_rdcng
Importance of reducing deficit
- biz_leaders_decide
Whether business leaders should make political decisions
- black_atttd_agree
Agree/disagree: past slavery & discrimination make it difficult for blacks
- black_atttd_agree_2
Agree/disagree: blacks should work their way up without special favors
- black_atttd_agree_if
Agree/disagree: if blacks tried harder they'd be as well off as whites
- black_atttd_agree_t
Agree/disagree: blacks have gotten less than they deserve
- bttr_worse_if_man
Better/worse if man works and woman takes care of home
- camp_fnnc_cong_chng
Congress change votes because of donation to campaign
- camp_fnnc_cong_pas_2
Congress pass laws that benefit contributor individuals
- camp_fnnc_cong_pass
Congress pass laws that benefit contributor organization
- camp_fnnc_lmts_camp
Limits on campaign spending
- camp_interest
Interest in following campaigns
- cares_wins_pres
How much respondent cares who wins the presidency
- case_id
2024 Time Series Case ID
- cell_phone
Does respondent personally have a cell phone
- child_brght_illglly
Should children brought illegally be sent back or allowed to stay
- child_household
How many children in HH age 0-17
- child_rrng_child_i_2
Which child trait more important: curiosity or good manners
- child_rrng_child_i_3
Which child trait more important: obedience or self-reliance
- child_rrng_child_i_4
Which child trait more important: considerate or well-behaved
- child_rrng_child_imp
Which child trait more important: independence or respect
- choice_satisfaction
Satisfaction with the range of choices in elections
- cncrn_govt_undrmn
Concern that government might undermine the news media
- cnsdr_thmslf_fmnst
Does respondent consider themself a feminist or anti-feminist
- cntrbt_any_other
respondent contribute to any other group that supported or opposed candidates
- cntry_bttr_off_if_we
Country would be better off if we just stayed home
- cntry_feel_irrttd
How irritated respondent feels about how things are going in the country
- cntry_right_track
Are things in the country on right track
- conf_2020_winner
How confident is respondent about that (winner of 2020 election)
- conf_2024_winner
How confident is respondent about that (winner of 2024 election)
- conf_hunter_biden
How confident is respondent about that (Hunter Biden)
- conf_jan6_events
How confident is respondent about that (events on January 6, 2021)
- conf_trump_russia
How confident is respondent about that (Trump colluded with Russia)
- corruption_change
Corruption increased/decreased since Biden became president
- corruption_wide
How widespread corruption is
- court_authority
Whether courts can stop the government from acting illegally
- covid_democracy
Effect of COVID on democracy
- covid_infection
Personal experience with COVID infection
- covid_personal_econ
Effect of COVID on respondent's personal finances
- covid_unity
Effect of COVID on national unity
- crrnt_unmplymnt_rate
What is the current unemployment rate
- dem_party_dislike
Whether respondent dislikes anything about the Democratic Party
- dem_party_like
Whether respondent likes anything about the Democratic Party
- dem_process_sat
Satisfaction with the democratic process
- democracy_best
Whether democracy is preferable to other forms of government
- dhs_wrrd_trrrst_near
How worried about terrorist attack in near future
- difficult_it_r_vote
How difficult was it for respondent to vote
- discrim_us_asian
Discrimination in the US against Asians
- discrim_us_black
Discrimination in the US against blacks
- discrim_us_christian
Discrimination in the US against Christians
- discrim_us_hispanic
Discrimination in the US against Hispanics
- discrim_us_men
Discrimination in the US against men
- discrim_us_muslim
Discrimination in the US against Muslims
- discrim_us_white
Discrimination in the US against whites
- discrim_us_women
Discrimination in the US against women
- dscrm_us_gay_lsbn
Discrimination in the US against Gays and Lesbians
- dscrm_us_trans_ppl
Discrimination in the US against transgender people
- econ_bttr_worse_next
Economy better or worse in next 12 months
- economic_mobility
Economic mobility
- economy_past_year
State of the economy over the past year
- effct_illgl_immig
effect of illegal immigration on crime rate
- elctns_make_govt_pay
Elections make government pay attention
- election_fairness
Perceived fairness of elections
- eqlty_blf_if_ppl_we
If people were treated more fairly we would have fewer problems
- eqlty_blf_not_big_if
Not a big problem if some have more chance in life
- eqlty_blf_scty_shld
Society should make sure everyone has equal opportunity
- eqlty_blf_we_d_be_if
We'd be better off if worried less about equality
- experts_decide
Whether independent experts should make political decisions
- exprnc_many_guns
How many guns in household
- exprnc_much_money
How much money does respondent owe in student loans
- family_members_home
Family members living with respondent
- favor_opps_allwng
Favor/oppose allowing felons to vote
- favor_opps_bckgrnd
Favor/oppose background checks for gun purchases
- favor_opps_bldng_mxc
Favor or oppose building a wall on border with Mexico
- favor_opps_bnnng
Favor/oppose banning 'assault-style' rifles
- favor_opps_bnnng_k
Favor/oppose banning transgender girls from K-12 girls sports
- favor_opps_endng
Favor or oppose ending birthright citizenship
- favor_opps_free
Favor/oppose free trade agreements
- favor_opps_govt_rdc
Favor/oppose government trying to reduce income inequality
- favor_opps_inc_rgltn
Favor/oppose increased regulation on greenhouse emissions
- favor_opps_laws_gay
Favor/oppose laws protect gays/lesbians against job discrimination
- favor_opps_new_lmts
Favor/oppose new limits on imports
- favor_opps_prfrntl
Favor/oppose preferential hiring/promotion of blacks
- favor_opps_prvdng
Favor/oppose providing path to citizenship
- favor_opps_right_gay
Favor/oppose right of gay and lesbian couples to legally marry
- favor_opps_rqrng
Favor/oppose requiring vaccines in schools
- favor_opps_rqrng_id
Favor/oppose requiring ID when voting
- favor_opps_rstrctng
Favor or oppose restricting journalist access
- favor_opps_trans_ppl
Favor/oppose transgender people serve in military
- favor_opps_us_gvng
Favor/oppose U.S. giving weapons to help Ukraine fight Russia
- favor_opps_us_gvng_2
Favor/oppose U.S. giving military assistance to Israel
- favor_opps_us_gvng_3
Favor/oppose U.S. giving humanitarian aid to Palestinians
- fed_bdgt_spend_aid
Federal Budget Spending: aid to the poor
- fed_bdgt_spend_bldng
Federal Budget Spending: building and repairing highways
- fed_bdgt_spend_brdr
Federal Budget Spending: Tightening border security
- fed_bdgt_spend_dlng
Federal Budget Spending: dealing with crime
- fed_bdgt_spend_env
Federal Budget Spending: protecting the environment
- fed_bdgt_spend_pblc
Federal Budget Spending: public schools
- fed_bdgt_spend_soc
Federal Budget Spending: Social Security
- fed_bdgt_spend_wlfr
Federal Budget Spending: welfare programs
- fed_govt_trts_black
Federal government treats blacks or whites better
- feel_afraid
How afraid respondent feels about the country
- feel_angry
How angry respondent feels about the country
- feel_happy
How happy respondent feels about the country
- feel_hopeful
How hopeful respondent feels about the country
- feel_nervous
How nervous respondent feels about the country
- feel_outraged
How outraged respondent feels about the country
- feel_proud
How proud respondent feels about the country
- feel_worried
How worried respondent feels about the country
- fin_borrowed
Has respondent done any of the following - borrowed money to pay bills
- fin_cc_debt
Has respondent done any of the following - took on credit card debt
- fin_cncrn_any_fmly
Have any family members or close friends lost jobs in last 12 months
- fin_cncrn_lkly_able
How likely respondent able to make all housing payments in next 12 months
- fin_cncrn_wrrd_crrnt
How worried is respondent about current financial situation
- fin_cut_spend
Has respondent done any of the following - cut down spending
- fin_next_year
Expected personal financial situation one year from now
- fin_none
Has respondent done any of the following - none of these
- fin_past_year
Personal financial situation compared with one year ago
- fin_postpone
Has respondent done any of the following - cancel/postpone major purchase
- fin_savings
Has respondent done any of the following - dipped into savings
- fin_strain_sum
Number of financial strain actions reported.
- fmly_nghbrs_cwrkrs
respondent has family/neighbors/coworkers/friends who are gay, lesbian or bisexual
- fmly_nghbrs_cwrkrs_1
respondent has family/neighbors/coworkers/friends who are transgender
- frgn_plcy_force
Force to solve international problems
- ft_asian_americans
Warmth rating of Asian-Americans
- ft_biden_post
Warmth rating of Joe Biden after the election
- ft_biden_pre
Warmth rating of Joe Biden before the election
- ft_big_business
Warmth rating of big business
- ft_black_lives_mttr
Warmth rating of Black Lives Matter
- ft_black_people
Warmth rating of Black people
- ft_christian_fund
Warmth rating of Christian fundamentalists
- ft_christians
Warmth rating of Christians
- ft_congress
Warmth rating of congress
- ft_conservatives
Warmth rating of conservatives
- ft_dem_party
Warmth rating of the Democratic Party
- ft_fbi
Warmth rating of Federal Bureau of Investigation (FBI)
- ft_feminists
Warmth rating of feminists
- ft_gay_men_lesbians
Warmth rating of gay men and lesbians
- ft_gretchen_whitmer
Warmth rating of Gretchen Whitmer
- ft_harris_post
Warmth rating of Kamala Harris after the election
- ft_harris_pre
Warmth rating of Kamala Harris before the election
- ft_hispanics
Warmth rating of Hispanics
- ft_illegal_immigs
Warmth rating of illegal immigrants
- ft_jews
Warmth rating of Jews
- ft_josh_shapiro
Warmth rating of Josh Shapiro
- ft_labor_unions
Warmth rating of labor unions
- ft_liberals
Warmth rating of liberals
- ft_maga
Warmth rating of Make America Great Again (MAGA)
- ft_mark_kelly
Warmth rating of Mark Kelly
- ft_muslims
Warmth rating of Muslims
- ft_nra
Warmth rating of National Rifle Association (NRA)
- ft_plnnd_prnthd
Warmth rating of Planned Parenthood
- ft_police
Warmth rating of police
- ft_rep_party
Warmth rating of the Republican Party
- ft_robert_kennedy_jr
Warmth rating of Robert Kennedy, Jr.
- ft_roy_cooper
Warmth rating of Roy Cooper
- ft_rural_americans
Warmth rating of rural Americans
- ft_sen_dem_cand
Warmth rating of Democratic Senate candidate
- ft_sen_rep_cand
Warmth rating of Republican Senate candidate
- ft_trans_people
Warmth rating of transgender people
- ft_trump_post
Warmth rating of Donald Trump after the election
- ft_trump_pre
Warmth rating of Donald Trump before the election
- ft_us_house_cand
Warmth rating of US House candidate that respondent voted for
- ft_us_supreme_court
Warmth rating of US Supreme Court
- ft_vance_post
Warmth rating of J.D. Vance after the election
- ft_vance_pre
Warmth rating of J.D. Vance before the election
- ft_walz_post
Warmth rating of Tim Walz after the election
- ft_walz_pre
Warmth rating of Tim Walz before the election
- ft_white_people
Warmth rating of White people
- gay_lsbn_cpls_allwd
Should gay/lesbian couples be allowed to adopt children or not
- gender_s_gender
What is respondent's gender?
- gender_s_sex
What is respondent's sex?
- gndr_cnsdr_thmslf_be
Does respondent consider themself to be transgender
- gndr_role_women_c
Do women complaining about discrimination cause more problems
- gndr_role_women_seek
Do women demanding equality seek special favors
- gndr_scale_fmnnty
respondent femininity scale
- gndr_scale_msclnty
respondent masculinity scale
- gndr_sxl_ornttn
Sexual orientation of respondent
- good_job_house_dist
How good a job does House incumbent do in district
- govt_4yr_perf
Government performance over the last four years
- govt_actn_rsng
Government action about rising temperatures
- govt_big_intrsts_all
Government run by a few big interests or for benefit of all
- govt_corrupt_extent
How widespread corruption is in government
- govt_health_care
Government responsibility for health care
- govt_more_less_opd
Should government do more/less about opioid drug addiction
- govt_wsts_tax_money
Does government waste much tax money
- group_inflnc_much
How much influence do Hispanics have in US politics
- group_inflnc_much__2
How much influence do blacks have in US politics
- group_inflnc_much__3
How much influence do Asians have in US politics
- group_inflnc_much_us
How much influence do whites have in US politics
- group_treatment
Whether some groups receive worse treatment than others
- gun_ownership_count
Number of guns respondent owns
- harris_trait_cares
Kamala Harris trait: really cares
- harris_trait_energy
Kamala Harris trait: energetic
- harris_trait_honest
Kamala Harris trait: honest
- harris_trait_know
Kamala Harris trait: knowledgeable
- harris_trait_lead
Kamala Harris trait: strong leadership
- has_children
Has any children
- has_daughters
Has one or more daughters
- has_sons
Has one or more sons
- health_health_ins
Does respondent have health insurance
- hispanic_summary
Hispanic ethnicity group
- hlpfl_hrmfl_if_pres
Helpful/harmful if president did not have to worry about congress/courts
- hlth_bnfts_vccntns
Health benefits of vaccinations outweigh risks
- hlth_cncrnd_lsng_ins
respondent concerned about losing health insurance
- hlth_cncrnd_pyng
respondent concerned about paying for health care
- hlth_trbl_cncntrtng
Trouble concentrating in past week
- house_vote_intent
Party of respondent's U.S. House vote intention or preference
- house_vote_party
Party of respondent's U.S. House vote
- house_vote_pref
Party of respondent's U.S. House vote or preference
- household_landline
Is there a working HH landline phone
- hshld_union_mmbr
Anyone in HH belong to labor union
- hunter_laptop_claim
Hunter Biden's laptop showed he made deal with Ukrainian and Chinese businesses
- id_dcmnt_valid_non
Does respondent have a valid, non-expired passport
- id_dcmnt_valid_non_s
Does respondent have a valid, non-expired driver's license
- immgs_gnrlly_good
Are immigrants generally good or bad for America's economy
- immig_crime
Belief that immigrants increander, sse crime
- imp_american_id
How important is being American to respondent's identity
- imp_elect_asian
How important that more Asians get elected to political office
- imp_elect_black_ppl
How important that more blacks get elected to political office
- imp_elect_hispanic
How important that more Hispanics get elected to political office
- imp_elect_lgbt_ppl
How important that more LGBT people get elected to political office
- imp_elect_woman_pres
How important that a woman be elected president of the US
- imp_elect_women
How important that more women get elected to political office
- imp_immgs_adapt_us
How important is it for immigrants to adapt to customs/traditions of the US
- imp_issue_abort
How important is the following issue: abortion
- imp_issue_clim_chng
How important is the following issue: climate change
- imp_issue_cost_lvng
How important is the following issue: cost of living
- imp_issue_crime
How important is the following issue: crime
- imp_issue_gun_policy
How important is the following issue: gun policy
- imp_issue_illgl
How important is the following issue: illegal immigration
- imp_issue_pblc_schls
How important is the following issue: what is taught in public schools
- imp_issue_rcl_ineq
How important is the following issue: racial inequality
- imp_issue_us_dmcrcy
How important is the following issue: US democracy
- imp_issue_war_gaza
How important is the following issue: War in Gaza
- imp_urban_rural_id
How important is urban or rural to respondent's identity
- imp_white_id
How important is being white to respondent's identity
- incrs_dcrs_govt_help
Increase/decrease government spending to help pay for health care
- incrsng_dvrsty_made
Increasing diversity made US better/worse place to live
- internet_at_home
Does respondent use Internet at home
- interview_status
Pre/Post Interview Completion Status
- intrvw_cntxt_stsfd
How satisfied is respondent with life
- it_be_good_scty_more
Would it be good for society to have more or less government regulation
- jan6_pro_trump
Events on January 6, 2021 were carried out by pro-Trump protestors or FBI agents
- job_satisfaction
How satisfied or dissatisfied is respondent with current job?
- laid_off_last_6
Working now: out of work or laid off in last 6 months
- legit_win_2020
Who was the legitimate winner of the 2020 presidential election
- legit_win_2024
Was Trump or Harris the legitimate winner of the 2024 presidential election
- less_or_more_govt
Less or more government
- life_exprnc_ever
Life experience: has respondent ever been bitten by a shark
- life_exprnc_gone_y
Life experience: has respondent gone hunting or fishing in past year
- life_exprnc_know_smn
Life experience: does respondent know someone moved to US from another country
- life_exprnc_used_pas
Life experience: has respondent used public transportation in past year
- like_dem_cand
Like-dislike rating of the Democratic presidential candidate
- like_dem_party
Like-dislike rating of the Democratic Party
- like_rep_cand
Like-dislike rating of the Republican presidential candidate
- like_rep_party
Like-dislike rating of the Republican Party
- likely_r_vote
How likely respondent is to vote
- lnkd_fate_white_ppl
White respondent: what happens to white people will affect respondent's life
- lr_dem_party
Left-right placement of the Democratic Party
- lr_rep_party
Left-right placement of the Republican Party
- lr_self
Respondent's left-right self-placement
- many_days_past_week
How many days in past week discussed politics with family or friends
- men_econ_crisis
Whether men or women are better suited to handle an economic crisis
- men_pandemic_lead
Whether men or women are better suited to handle a pandemic
- mode_post
Interview mode after the election
- mode_pre
Interview mode before the election
- mrlty_blf_fewer_if
Fewer problems if there was more emphasis on traditional family values
- mrlty_blf_world_we
The world is changing & we should adjust view of moral behavior
- mrtl_stts_5_ctgry
Marital status (5 category)
- much_dscrm_faced_bcs
How much discrimination has respondent faced personally because or race/ethnicity
- much_lrgr_incm_gap
How much larger is income gap today
- much_pol_dffrncs
How much have political differences hurt relationships w/family
- much_pol_vlnc_inc
How much has political violence increased/decreased compared to 4 yrs ago
- natid_born_us
Importance of being born in the United States for national identity
- natid_speak_english
Importance of speaking English for national identity
- natl_econ_bttr_worse
National economy better or worse in last year
- news_newspaper
Frequency of reading newspapers
- news_online
Frequency of visiting online news sites
- news_private_tv
Frequency of watching news on private television
- news_public_tv
Frequency of watching news on public television
- news_radio
Frequency of listening to news on radio
- news_social_media
Frequency of using social media for news
- often_bght_bycttd
How often bought or boycotted product/service for social/political reasons
- often_plc_offcrs_use
How often do police officers use more force than necessary
- often_votes_cntd
How often are votes counted fairly
- party_better_crime
Which party would do a better job handling: crime
- party_better_economy
Which party better: handling nations economy
- party_control
Preference for one-party or split-party government
- party_id
Party ID
- partyid3
Party ID, 3 categories
- past_12_mnths_attnd
Has respondent in past 12 months: attend mtg about issue facing community/schools
- past_12_mnths_cntctd
Has respondent in past 12 months: contacted federal elected official
- past_12_mnths_done
Has respondent in past 12 months: done any volunteer work
- past_12_mnths_given
Has respondent in past 12 months: given money to other organization
- past_12_mnths_gttn
Has respondent in past 12 months: gotten into a political argument with someone
- past_12_mnths_jnd
Has respondent in past 12 months: joined a protest march, rally, or demonstration
- past_12_mnths_pstd
Has respondent in past 12 months: posted comment online about political issue
- past_12_mnths_sign
Has respondent in past 12 months: sign internet or paper petition
- plc_exprnc_drng_past
During past 12 months, respondent or any family members stopped by police
- plc_exprnc_ever_been
Has respondent ever been arrested
- plc_treat_black_bttr
Police treat blacks or whites better
- pol_attention
Attention to politics and elections
- pol_interest
Interest in politics
- pol_know_many_years
How many years in full term for US Senator
- pol_know_prgrm_fed
On which program does Federal government spend the least
- pol_know_pty_most
Party with most members in Senate before election
- pol_know_pty_most_e
Party with most members in House before election
- ppl_rural_areas_ge_2
People in rural areas get too much/too little respect
- ppl_rural_areas_get
People in rural areas get more/less from government
- ppl_rural_areas_too
People in rural areas have too much/too little influence
- pres_covid_perf
president's handling of COVID
- pres_primary_vote
Whether respondent voted in a presidential primary or caucus
- pres_two_way_vote
Choice if presidential election were only Harris and Trump
- pres_vote_2016_rcll
Recall of 2016 presidential vote choice
- pres_vote_2024
presidential vote in 2024
- pres_vote_intent
Whether respondent intended to vote for president
- pres_vote_intnt_chc
For whom does respondent intend to vote for president
- pres_vote_party
Party of respondent's presidential vote intention or preference
- pres_vote_pref
presidential vote or preference
- pres_vote_strength
Strength of presidential vote preference
- prfr_gov_offcl_stcks
Prefer government official who compromises/sticks to principles
- pty_better_abort
Which party would do a better job handling: abortion
- pty_better_env
Which party better: handling environment
- pty_better_immig
Which party better: handling immigration
- pty_bttr_clim_chng
Which party would do a better job handling: climate change
- pty_bttr_cost_lvng
Which party would do a better job handling: cost of living
- pty_bttr_illgl_immig
Which party would do a better job handling: illegal immigration
- pty_bttr_tght_pblc
Which party would do a better job handling: what is taught in public schools
- pty_contact_r_camp
Which party contact respondent about campaign
- pty_id_imp
Party identity importance
- r_5_ctgry_level_educ
Respondent 5 Category level of education
- r_age_election_day
Respondent age on Election Day
- r_favor_opps_affrmtv
Does respondent favor/oppose affirmative action in universities
- r_favor_opps_death
respondent favor/oppose death penalty
- r_occptn_stts_1
respondent occupation status 1 digit
- r_rgstr_vote_first
When did respondent register to vote for the first time
- r_self_idntfd_race
respondent self-identified race/ethnicity
- r_side_more_isrls
Does respondent side more with Israelis or Palestinians
- r_sps_prtnr_5_ctgry
Respondent spouse/partner 5 Category level of education
- r_sps_prtnr_race
respondent spouse or partner race/ethnicity
- r_think_they_get
Does respondent think they get more or less than their fair share in life
- r_usually_vote
How does respondent usually vote
- r_voted_2024_elctn
When respondent voted in 2024 election
- r_voted_2024_elctn_2
How respondent voted in 2024 election
- race_atttd_often
How often does respondent have concerned feelings for other racial/ethnic groups
- race_atttd_often_2
How often respondent imagines how they would feel before criticizing other groups
- race_atttd_often_smn
How often respondent feels protective of someone due to race or ethnicity
- race_atttd_often_try
How often does respondent try to understand perspective of other racial/ethnic groups
- rcll_2020_pres_vote
Recall of last (2020) presidential vote
- recall_chief_jus
Consolidated office-recall score for U.S. Supreme Court Chief Justice Roberts.
- recall_fr_pres
Consolidated office-recall score for French president Emmanuel Macron.
- recall_ru_pres
Consolidated office-recall score for Russian president Vladimir Putin.
- recall_sen_lead
Consolidated office-recall score for Senate Majority Leader Schumer.
- recall_speaker
Consolidated office-recall score for Speaker of the House Johnson.
- referendums_decide
Whether citizen referendums should make political decisions
- reg_pty_reg_state
Party registration in state of registration (pre nonvoter)
- registered_voter
Whether respondent is registered to vote
- registration_state
Voter registration status
- religion_detail
Detailed religious tradition
- religion_major_grp
Major religious tradition
- rep_party_dislike
Whether respondent dislikes anything about the Republican Party
- rep_party_like
Whether respondent likes anything about the Republican Party
- rqr_emplyrs_offer
Require employers to offer paid leave to parents of new children
- sample_census_region
SAMPLE: Census region
- sample_type
Sample Type
- scale_abort_dem_pres
Position on abortion: Democratic presidential candidate
- scale_abort_rep_pres
Position on abortion: Republican presidential candidate
- scale_aid_black_dem
Position on government assistance to blacks scale: Democratic presidential candidate
- scale_aid_black_rep
Position on government assistance to blacks scale: Republican presidential candidate
- scale_aid_black_self
Position on government assistance to blacks scale: self-placement
- scale_defense_self
Position on defense spending: self-placement
- scale_dfns_dem_pres
Position on defense spending: Democratic presidential candidate
- scale_dfns_rep_pres
Position on defense spending: Republican presidential candidate
- scale_env_bsnss_dem
Position on environment-business tradeoff: Democratic presidential candidate
- scale_env_bsnss_rep
Position on environment-business tradeoff: Republican presidential candidate
- scale_env_bsnss_self
Position on environment-business tradeoff: self-placement
- scale_hlth_ins_dem
Position on government-private medical insurance scale: Democratic presidential candidate
- scale_hlth_ins_rep
Position on government-private medical insurance scale: Republican presidential candidate
- scale_hlth_ins_self
Position on government-private medical insurance scale: self-placement
- scale_jobs_incm_dem
Position on guaranteed job-income scale: Democratic presidential candidate
- scale_jobs_incm_rep
Position on guaranteed job-income scale: Republican presidential candidate
- scale_jobs_incm_self
Position on guaranteed job-income scale: self-placement
- scale_lbcn_dem_house
Position on liberal-conservative: Democratic House candidate
- scale_lbcn_dem_pres
Position on liberal-conservative: Democratic presidential candidate
- scale_lbcn_rep_house
Position on liberal-conservative: Republican House candidate
- scale_lbcn_rep_pres
Position on liberal-conservative: Republican presidential candidate
- scale_libcon_dem_pty
Position on liberal-conservative: Democratic party
- scale_libcon_rep_pty
Position on liberal-conservative: Republican party
- scale_libcon_self
Position on liberal-conservative self-placement
- scale_services_self
Position on spending & services: self-placement
- scale_svc_dem_pres
Position on spending & services: Democratic presidential candidate
- scale_svc_rep_pres
Position on spending & services: Republican presidential candidate
- self_cnsr_need_be
Need to be more sensitive talking or people too easily offended
- self_cnsr_often_self
How often does respondent self censor
- senate_vote_intent
Party of respondent's U.S. Senate vote intention or preference
- shld_mnmm_wage_be
Should the minimum wage be raised, kept the same, or lowered
- smpl_smpl_lctn_state
SAMPLE: Sample location state postal abbreviation
- soc_class_dscrb_soc
How would respondent describe social class [EGSS]
- soc_med_use_often
How often use Facebook
- soc_med_use_often_2
How often post political content on Facebook
- socmed_facebook
Which social media platforms respondent visited - Facebook [mention]
- socmed_instagram
Which social media platforms respondent visited - Instagram [mention]
- socmed_other
Which social media platforms respondent visited - Other [mention]
- socmed_plat_sum
Number of social media platforms visited.
- socmed_reddit
Which social media platforms respondent visited - Reddit [mention]
- socmed_snapchat
Which social media platforms respondent visited - SnapChat [mention]
- socmed_tiktok
Which social media platforms respondent visited - TikTok [mention]
- socmed_twitter
Which social media platforms respondent visited - Twitter [mention]
- socmed_youtube
Which social media platforms respondent visited - YouTube [mention]
- split_ticket_vote
Whether respondent votes a straight or split ticket
- sps_prtnr_gndr
respondent spouse/partner gender
- stereo_black_violent
Stereotype: Blacks violent
- stereo_white_violent
Stereotype: Whites violent
- str_asian_amrcns
Stereotype: Asian-Americans hardworking
- str_asian_amrcns_2
Stereotype: Asian-Americans violent
- str_black_hrdwrkng
Stereotype: Blacks hardworking
- str_hspnc_hrdwrkng
Stereotype: Hispanics hardworking
- str_hspnc_vlnt
Stereotype: Hispanics violent
- str_white_hrdwrkng
Stereotype: Whites hardworking
- strong_leader_good
Whether having a strong leader in government is good
- talk_frnds_fmly_live
Does respondent talk to friends/family who live in other countries about events in that country
- threat_china
How much is China a threat to the United States
- threat_iran
How much is Iran a threat to the United States
- threat_israel
How much is Israel a threat to the United States
- threat_japan
How much is Japan a threat to the United States
- threat_mexico
How much is Mexico a threat to the United States
- threat_russia
How much is Russia a threat to the United States
- total_hshld_incm
Total (household) income
- total_hshld_incm_2
Total (household) income [six category]
- trans_sports_ban
Support for banning transgender girls from girls' sports
- trump_courts_fair
Have the courts treated Donald Trump fairly or unfairly
- trump_courts_fair2
Courts treated Donald Trump fairly/unfairly
- trump_jury_verdict
Manhattan jury that found Trump guilty made right/wrong decision
- trump_russia_claim
Donald Trump's campaign colluded with Russian government in 2016
- trump_trait_cares
Donald Trump trait: really cares
- trump_trait_energy
Donald Trump trait: energetic
- trump_trait_honest
Donald Trump trait: honest
- trump_trait_know
Donald Trump trait: knowledgeable
- trump_trait_lead
Donald Trump trait: strong leadership
- trust_congress
Trust in Congress
- trust_courts
How often can you trust the court system to do what is right
- trust_effccy_no_say
Have no say about what government does
- trust_effccy_pblc_t
Public officials don't care what people think
- trust_effccy_pol_too
Politics/government too complicated to understand
- trust_effccy_well
How well does respondent understand important political issues
- trust_federal_govt
How often trust government in Washington to do what is right
- trust_govt
Trust in government
- trust_judiciary
Trust in the judiciary
- trust_news_media
Trust and confidence in the news media
- trust_parties
Trust in political parties
- trust_people
How often can people be trusted
- trust_scientists
Trust in scientists
- trust_soc_media
Trust in social media
- trust_trad_media
Trust in traditional media
- understands_issues
Agreement that respondent understands important political issues
- unmplymnt_bttr_worse
Unemployment better or worse in last year
- unmplymnt_next_year
More or less unemployment in next year
- urban_unrest_force
Preferred response to urban unrest
- us_bttr_worse_than
US better or worse than most other countries
- us_democracy_scale
Rating of how democratic the United States is
- uslly_think_self_as
Does respondent usually think of self as a rural or urban person
- vccn_conf_vccns_au
How confident is respondent about that (vaccines cause autism)
- vccn_most_scntfc_cau
Does most scientific evidence show vaccines cause autism or not
- vote_as_duty_choice
Voting as duty or choice
- vote_makes_diff
Whether who people vote for makes a difference
- vote_prob_abs
Did respondent encounter any problems voting - difficulty obtaining absentee ballot
- vote_prob_ballot
Did respondent encounter any problems voting - confusion about ballot or machine
- vote_prob_id
Did respondent encounter any problems voting - concern about identification card
- vote_prob_mail
Did respondent encounter any problems voting - issue mailing ballot
- vote_prob_no_try
Did respondent encounter any problems voting - respondent didn't try to vote
- vote_prob_none
Did respondent encounter any problems voting - none at all
- vote_prob_other
Did respondent encounter any problems voting - other problem
- vote_prob_reg
Did respondent encounter any problems voting - registration problem
- vote_prob_sum
Number of voting problems reported.
- vote_prob_transp
Did respondent encounter any problems voting - difficulty getting to polling place
- vote_prob_wait
Did respondent encounter any problems voting - long wait times
- vote_prob_weather
Did respondent encounter any problems voting - bad weather
- vote_prob_work
Did respondent encounter any problems voting - work schedule
- vote_satisfaction
Satisfaction with how people voted in the election
- voted_early
Whether respondent had already voted early
- voted_president_2016
Did respondent vote for president in 2016 election
- voter_turnout
Voter turnout in 2024
- women_blf_agree_dsgr
Agree/disagree - women interpret innocent remarks as sexist
- women_blf_women_seek
Women seek to gain power by getting control over men
- women_congress_share
Whether the share of women in Congress is too high or too low
- women_rep_policy
Support for policies to increase women's representation
- work_hours_pay_cut
Working now: had reduction in work hrs or pay cut
- work_hrssmnt_exprncd
Has respondent experienced harassment at work
- world_tmprtr_conf_t
How confident is respondent about that (world temperatures have risen)
- world_tmprtr_world
Have world temperatures have risen on average or last 100 years or not
- worried_losing_job
Working now: worry about losing job in near future
- wt
Analysis weight for the pre-election survey
- wt_post
Analysis weight for the post-election survey
Source
American National Election Studies. 2024 Time Series Study Full Release.
Generates box plots to compare interval-level dependent variable's distribution across categories of independent variable.
Description
Generates box plots for visual comparison of interval-level dependent variable's distribution across categories of independent variable. Includes option for weighting observations, modifying colors, variable widths. Box plot can be used to compare values of interval-level dependent variable by categories of an independent variable (a factor). If iv is omitted, the function creates a single-variable box plot.
Usage
boxplotC(dv, iv = NULL, w = NULL, data = NULL, main = NULL,
xlab = NULL, ylab = NULL, box.col = "gray80", varwidth = TRUE,
ivlabs = NULL, printC = FALSE, ...)
Arguments
dv |
Dependent variable, should be in dataset$var form unless dataset specified in optional data argument. |
iv |
(Optional) Independent variable, should be in dataset$var form unless dataset specified in optional data argument. If omitted or set to |
w |
(Optional) Sampling weights of variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains dv, iv (and w) variables (optional). |
main |
(Optional) Supply custom main label for plot; default uses names of dv and iv (or just dv if |
xlab |
(Optional) Supply custom x-axis label for plot; default uses name of iv when provided, and blank label when |
ylab |
(Optional) Supply y-axis label for plot; default uses name of dv. |
box.col |
(Optional) The name of color to use for box fills. Default is "gray80". Border color follows |
varwidth |
(Optional) Do you want the widths of boxes to be proportional to number of observations in each group? Default is TRUE; set |
ivlabs |
(Optional) A vector of labels for the iv values that are box lablels. |
printC |
(Optional) Do you want to print box plot to .html file in working directory? (Default: FALSE) |
... |
Additional arguments passed to |
Details
Numeric-looking factor or character labels, such as "10" and "20", are interpreted as their displayed numeric values for the dependent variable.
Value
Invisibly returns the bxp_input object used to draw the plot
(class "boxplot"), including computed boxplot statistics by group.
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
RCPA4 Package Tutorial Videos
-
Making Box Plots with RCPA4's boxplotC Function 15:12, shows you how to use the RCPA4 Package's boxplotC function to create box plots that show the relationship between an interval-level dependent variables and a categorical independent variable.
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 5.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp. 53-55. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Graphing Relationships and Describing Patterns, compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site, find datasets for your own research and resources to help with political analysis.
Examples
library(RCPA4)
# basic usage with variables as vectors
boxplotC(dv=anes$ft_rep_party, iv=anes$partyid3)
# single-variable box plot
boxplotC(dv=anes$ft_rep_party)
Mean comparison analysis function, makes controlled comparisons, generates plots, performs ANOVA
Description
Mean comparison analysis, options for weighted observations and control variable. Also supports several plotting options for basic mean comparisons and controlled mean comparisons. Can conduct single and two-factor analysis of variance (ANOVA) to test differences among multiple means.
Usage
compmeansC(dv, iv, w = NULL, z = NULL, data = NULL, digits = 2,
compact = FALSE, ivlabs = NULL, zlabs = NULL, anova = FALSE,
printC = FALSE, plot = TRUE, main = NULL, xlab = NULL, ylab = NULL,
ylim = NULL, plot.ci = FALSE, z.palette = "LightGrays",
legend.title = NULL, table = TRUE)
Arguments
dv |
Dependent variable, should be in dataset$var form unless dataset specified in optional data argument. |
iv |
Independent variable, should be in dataset$var form unless dataset specified in optional data argument. |
w |
(Optional) Sampling weights of variable (optional), must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
z |
(Optional) Control variable, must be a factor; should be in dataset$z form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains dv, iv (and w) variables (optional). |
digits |
(Optional) The number of decimal places reported in result (defaults to 2). |
compact |
(Optional) Do you want compact version of controlled mean comparison table with N and Std. Dev. values omitted? Default is FALSE. Compact display only available for controlled comparisons. |
ivlabs |
(Optional) A vector of names for the independent variable's values (to abbreviate the mean comparison table's row labels and iv labels on plots) |
zlabs |
(Optional) A vector of names for the control variable's values (to abbreviate a controlled mean comparison table's column labels and z variable's labels on plots) |
anova |
(Optional) Do you want to conduct analysis of variance (ANOVA)? Default is FALSE. |
printC |
(Optional) Do you want results printed to .html file in your working directory? Default is FALSE. Set to TRUE to print results. |
plot |
(Optional) Do you want a plot of the means? Default is TRUE (makes a bar plot). Additional options:
|
main |
(Optional) Main label for plot, if missing, default main title generated. |
xlab |
(Optional) x-axis label for plot, if missing, default label generated using iv name. |
ylab |
(Optional) y-axis label for plot, if missing, default label generated using dv name. |
ylim |
(Optional) Range of y-axis values on plot. |
plot.ci |
(Optional) Do you want vertical 95 percent confidence intervals added to line plot of means? Default is FALSE. Only works when |
z.palette |
(Optional) For bar and line charts with control variables (z), the name of HCL color palette to use. Default is "LightGrays". See |
legend.title |
(Optional) Customize title of legend on plot used for controlling comparisons. |
table |
(Optional) Do you want mean comparison table(s) reported? (default: TRUE) |
Value
Returns an augmented mean comparison table as a matrix of values.
Auxiliary tables are available via [[ (for example
out[["anova_table"]] or out[["controlled_panel_tables"]]).
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
Table and plot requirements
At least one of table or plot must be enabled. When using table = FALSE,
keep a valid plot enabled.
RCPA4 Package Tutorial Videos
-
Make Mean Comparisons with RCPA4's compmeansC Function 13:20, shows you how to use the RCPA4 Package's compmeansC function to compare values of an interval-level dependent variable across categories of an independent variable.
-
Making Controlled Mean Comparisons with RCPA4's compmeansC Function 25:46
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapters 4, 5, 7, 10.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp.85-97, 150-156. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Making Comparisons, Graphing Relationships and Describing Patterns, Making Controlled Comparisons, and Chi-Square Test and Analysis of Variance, compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
compmeansC(dv=anes$ft_rep_party, iv=anes$party_id, plot=FALSE)
# basic usage with a plot
compmeansC(dv=anes$ft_rep_party, iv=anes$party_id, w=anes$wt, plot=TRUE)
# basic usage: data argument used
compmeansC(dv=infant_mortality, iv=region, data=world, plot=FALSE)
# with weights and z variable
compmeansC(dv=anes$ft_rep_party, iv=anes$party_id, w=anes$wt, z=anes$gender_s_sex, plot="line")
compmeansC(
dv=anes$ft_gay_men_lesbians, iv=anes$gender_s_sex,
z=anes$partyid3, compact=TRUE, plot=TRUE
)
Correlation analysis for two or more numeric variables, with options for scatterplots, weighted observations, and inferential statistics.
Description
Given two or more numeric variables, correlateC reports Pearson's r, along with inferential statistics (if requested), works with sampling weights. If more than two x variables are supplied, the function calculates Pearson's r values using pairwise complete observations (as opposed to limiting analysis to observations complete on all variables).
Usage
correlateC(x, w = NULL, data = NULL, digits = 3, stats = FALSE,
printC = FALSE, plot = FALSE, jitter = FALSE, table = TRUE, ...)
Arguments
x |
A list of variables for correlation analysis, variables must be numeric. Should be entered as list(dataset$var1, dataset$var2, dataset$var3 ... ) form unless dataset specified in optional data argument. |
w |
(Optional) Sampling weights variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains x (and w) variable (optional). |
digits |
(Optional) Number of decimal places reported in result (defaults to 3). |
stats |
(Optional) Do you want the inferential statistics (standard errors, t-statistics, and P-values)? Default is FALSE. Set to TRUE for inferential statistics. |
printC |
(Optional) Do you want results printed to .html file in your working directory? Default is FALSE. Set to TRUE to print results. |
plot |
(Optional) Do you want scatterplot(s)? Default is FALSE. |
jitter |
(Optional) Do you want scatterplot pointed jittered? By default, points jittered when there are more than 500 observations, but you can set this arguments to TRUE/FALSE to override the default. |
table |
(Optional) Do you want correlation table(s) reported? (default: TRUE) |
... |
(Optional) Additional arguments passed to the internal weighted correlation helper. |
Details
Correlations are computed internally with optional weights and pairwise-complete handling for multivariate input.
Value
Returns the coefficients of correlation among x variables; if stats=TRUE, inferential statistics returned in tables as well.
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
Table and plot requirements
At least one of table or plot must be enabled. When using table = FALSE,
keep a valid plot enabled.
RCPA4 Package Tutorial Videos
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 11.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp. 240-244. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Correlation and Bivariate Regression, compiled by Barry C. Edwards.
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
correlateC(x=list(prochoice_percent, stateleg_women), data=states, plot=FALSE)
# with weighted observations and inferential statistics
correlateC(x=list(anes$ft_rep_party, anes$ft_trump_pre, anes$ft_dem_party, anes$ft_biden_pre),
w=anes$wt, stats=TRUE)
Cross-tabulation analysis, option for weighting observations, makes controlled comparisons, generates plots, performs Chi-Square test, measures strength of association
Description
This is a workhorse function for analyzing the relationship between two variables measured at the nominal or ordinal-level (factors). Basic output is a cross-tabulation with column percentages and counts. Options include weighting observations, adding control variable for controlled cross-tabulation, several plotting options, conducting Chi-Square test of independence, and measuring strength of association.
Usage
crosstabC(dv, iv, w = NULL, z = NULL, data = NULL, digits = 2,
compact = FALSE, dvlabs = NULL, ivlabs = NULL, zlabs = NULL,
chisq = FALSE, lambda = FALSE, somers = FALSE, cramers = FALSE,
printC = FALSE, plot = TRUE, plot.response = NULL, main = NULL,
xlab = NULL, ylab = NULL, z.palette = "LightGrays",
legend.title = NULL, table = TRUE)
Arguments
dv |
Dependent variable, should be in dataset$var form unless dataset specified in optional data argument. Should be a nominal or ordinal-level variable. |
iv |
Independent variable, should be in dataset$var form unless dataset specified in optional data argument. Should be a nominal or ordinal-level variable. |
w |
(Optional) Sampling weights of variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
z |
(Optional) Control variable, must be a facttor; should be in dataset$z form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains dv, iv (and w) variables. |
digits |
(Optional) Number of decimal places reported in result (defaults to 2). |
compact |
(Optional) Do you want compact display of cross-tabulation with row subtotals omitted? Default is FALSE. |
dvlabs |
(Optional) A vector of names for the dependent variable's values (to abbreviate the cross-tabulation's row labels and dv labels on plots) |
ivlabs |
(Optional) A vector of names for the independent variable's values (to abbreviate the cross-tabulation's column labels and iv labels on plots) |
zlabs |
(Optional) A vector of names for the control variable's values (to abbreviate the controlled cross-tabulation's column labels and z variable labels on plots) |
chisq |
(Optional) Do you want to conduct Chi-Square Test? If z argument specific, Chi-Square Test conducted on dv-iv relationship for each value of z. |
lambda |
(Optional) Do you want Lambda reported? If z argument specified, Lambda reported for dv-iv relationship for each value of z. |
somers |
(Optional) Do you want Somers' d reported? If z argument specific, Somers' D reported for dv-iv relationship for each value of z. |
cramers |
(Optional) Do you want Cramer's V reported? If z argument specific, Cramer's V reported for dv-iv relationship for each value of z. |
printC |
(Optional) Do you want to print cross-tabulation and plot (if plot is used) to .html file in working directory? (default: FALSE) |
plot |
(Optional) Do you want a plot of the cross-tabulation? Default is TRUE (and makes a bar plot). Other plot options:
|
plot.response |
(Optional) The dv value to be summarized on plot. To combine and plot multiple dv values, use transformC and create dummy variable to be plotted. Set |
main |
(Optional) Main label for plot |
xlab |
(Optional) x-axislabel for plot |
ylab |
(Optional) y-axis label for plot |
z.palette |
(Optional) For bar and line plots with control variables (z), the name of HCL color palette to use. Default is "LightGrays". See |
legend.title |
(Optional) Title for legend shown if plot used with z argument. |
table |
(Optional) Do you want cross-tabulation and statistics tables reported? (default: TRUE) |
Value
Returns an augmented cross-tabulation matrix. Auxiliary tables are
available via [[ (for example out[["chisq_table"]] or
out[["association_table"]]).
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
Table and plot requirements
At least one of table or plot must be enabled. When using table = FALSE,
keep a valid plot enabled.
RCPA4 Package Tutorial Videos
-
Create Cross-Tabulations to Make Comparisons with RCPA4's crosstabC Function 13:31
-
Plots for Cross-Tabulations with RCPA4's crosstabC Function 29:51
-
Making Controlled Comparisons with RCPA4's crosstabC Function 28:34
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapters 4, 5, 7, 10.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp.85-97, 150-156, 215-231. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
Tutorials & Resources for Making Comparisons, Graphing Relationships and Describing Patterns, Making Controlled Comparisons, and Chi-Square Test and Analysis of Variance, compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
crosstabC(dv=anes$r_favor_opps_death, iv=anes$partyid3)
# with optional w, data, chisq, somers arguments
crosstabC(dv=r_favor_opps_death, iv=partyid3, w=wt, data=anes, chisq=TRUE, somers=TRUE)
# example with optional w, data, z, and plot="line" arguments
crosstabC(dv=r_favor_opps_death, iv=partyid3, w=wt, data=anes, z=gender_s_sex, plot="line")
Debate Experiment dataset for R Companion to Political Analysis, Fourth Edition
Description
A dataset with variables about students who participated in an experiment. This dataset is used to demonstrate application of R to political analysis. See book Appendix for variable names and descriptions.
Format
A data frame with 171 rows and 14 variables.
- obs
Unique identification number for each subject
- assignment
Name of condition subject was assigned to
- tv
Did subject watch debate on TV?
- debinfo
Number of correct answers on five-question quiz about the debate
- catholic
Is subject Catholic?
- issues
Which candidate do you agree with on policy issues?
- integrity
Which candidate has more integrity?
- leadership
Which candidate is the more effective leader?
- empathy
Which candidate has more empathy?
- sophdum
Is respondent a sophomore?
- won
Which candidate won the debate?
- pid
Self-reported partisan identification
- ideology
Self-reported political ideology
- gender
Subject's gender
Source
Jamie Druckman. See Appendix of printed textbook for further information.
Generates table of descriptive statistics for one or more variables in a dataset
Description
Generates a table of descriptive statistics for variable(s) specified with x argument, displaying it by default. Works with variables measures at any level but output varies with level of measurement (e.g. you won't get standard deviation for a nominal variable). Character values are analyzed as categorical factors; the function does not convert variables to numeric or ordered classes, but provides class-specific guidance after reporting results. Option for weighting observations.
Usage
describeC(x, w = NULL, data = NULL, digits = 3, printC = FALSE,
table = TRUE)
Arguments
x |
A variable or list of variables, should be in dataset$var form unless dataset specified in optional data argument. |
w |
(Optional) Sampling weights of variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains x (and w) variable. |
digits |
(Optional) Number of decimal places reported in result (defaults to 3). |
printC |
(Optional) Do you want to print table of descriptive statistics to .html file in working directory? (default: FALSE) |
table |
(Optional) Display the descriptive-statistics table? Defaults to
|
Value
Invisibly returns a table of descriptive statistics, including when
table = FALSE. Assign the function call to an object to store the results.
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
Returning results without display
With table = FALSE, the table and its heading are omitted and no HTML
output is written, even if printC = TRUE. Class-specific informational
messages can still occur; use suppressMessages() to suppress those too.
RCPA4 Package Tutorial Videos
-
Generate Descriptive Statistics with RCPA4 Package's describeC Function 17:40
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 2.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp. 39-55. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
Tutorials & Resources for Descriptive Statistics, Compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
# descriptive statistics for qualitative variables
describeC(x=world$region)
# store results without displaying the table
statistics <- describeC(x=world$infant_mortality, table=FALSE)
# descriptive statistics for numeric variable
describeC(x=world$infant_mortality)
# describe multiple variables in list, with optional w argument
describeC(x=list(anes$feel_angry, anes$appr_cong_hndl_its), w=anes$wt)
Calculates model fit statistics for a svyglm linear regression model
Description
Model fit statistics for a svyglm weighted linear regression model (not for weighted logistic regression).
Usage
fit_svyglm(svyglm, digits = 3)
Arguments
svyglm |
An object of type svyglm. This object is the output of the svyglm function as well as regC function with w argument. |
digits |
Number of digits to report after decimal place, optional (default = 3). |
Details
With weighted logistic regression, McFadden's R2 is the same as the R-squared from this function, and adjusted R-squared is generally not used.
Value
Returns a numeric vector of R-Squared and Adjusted R-sSquared statistics.
Examples
library(RCPA4)
ft.police.model <- regC(ft_police ~ r_self_idntfd_race, w=wt, data=anes)
fit_svyglm(ft.police.model)
Reports the frequency distribution of dataset variable with table and bar chart
Description
Generates a frequency distribution table and bar chart to describe the distribution of variable values. Supports optional case weights.
Includes cumulative percents for ordered factors and for numeric variables
(treating numeric values as ordered categories), except when x has only
two values.
Usage
freqC(x, w = NULL, data = NULL, digits = 2, rowlabs = NULL,
printC = FALSE, plot = TRUE, main = NULL, xlab = NULL, ylab = NULL,
bar.col = "gray80", ylim = NULL, table = TRUE, ...)
Arguments
x |
The variable to be analyzed. If dataset not specified with data argument, should be a vector in form dataset$var. |
w |
(Optional) Sample weights (must be numeric if used), If dataset not specified with data argument, should be in form dataset$weighvar |
data |
(Optional) Name of dataset that contains x (and w) variable. |
digits |
(Optional) Number of digits to display after decimal point (default=2). |
rowlabs |
(Optional) Vector specifying custom text for labeling table rows and chart bars. The rowlabs vector must correspond to x variable's levels (if the variable has five levels, rowlabs must be length 5). Useful when default value labels are too long. |
printC |
(Optional) Do you want to print frequency distribution table and bar chart (if plot is used) to .html file in working directory? (default: FALSE) |
plot |
(Optional) Do you want a bar chart? (default set to TRUE) |
main |
(Optional) Main title of bar chart. |
xlab |
(Optional) The x-axis label of bar chart. |
ylab |
(Optional) The y-axis label of bar chart. |
bar.col |
(Optional) The name of color to use for bars. Default is "gray80". |
ylim |
(Optional) y-axis range for bar chart. If omitted, upper bound is set to the next multiple of 10 above the largest percent in table rows (excluding the Total row). |
table |
(Optional) Do you want the frequency distribution table reported? (default: TRUE) |
... |
(Optional) Additional arguments passed to |
Value
Invisibly returns a frequency distribution table (data frame) with
numeric frequencies and percentages. The digits argument controls display
formatting, not stored numeric values.
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
Table and plot requirements
At least one of table or plot must be enabled. When using table = FALSE,
keep a valid plot enabled.
RCPA4 Package Tutorial Videos
-
Make Frequency Distribution Tables and Bar Charts with RCPA4 Package's freqC Function 15:33
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 2.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp. 39-55. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Descriptive Statistics, compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
# unordered factors
freqC(x=region, data=world)
# ordered factors
freqC(x=threat_china, w=wt, data=anes)
Imports common dataset file types into R environment
Description
If you don't complete file argument, you will be prompted to select one. Supports common dataset file formats, including CSV, Stata, SPSS, native R, and SAS files. It previews imported data and asks you to confirm before returning a data frame. You must assign this returned object to a name to work with it. Native R files with multiple objects are returned as a named list. If getC doesn't support a file type, it suggests another function or package when possible.
Usage
getC(file = NULL, confirm = TRUE, ...)
Arguments
file |
(Optional) Local path or URL of the file you want to load into your R session; if you do not specify a file, you will be prompted to select one. |
confirm |
(Optional) Do you want to confirm getting file before function results returned? (default: TRUE) |
... |
(Optional) Additional arguments passed to loading function |
Details
A .sas7bdat file contains the SAS dataset. If it has a companion .sas7bcat catalog file, that catalog may supply value labels. Catalogs commonly have the same file name as the data file but a .sas7bcat extension. Provide its path with catalog_file, for example getC("survey.sas7bdat", catalog_file="survey.sas7bcat"). Files compressed with .gz, .bz2, or .xz are supported when their underlying file extension is supported, such as .csv.gz or .dta.gz.
Value
Dataset specified in file argument as a data frame. Native R files containing multiple objects return a named list. You must assign the returned object to a name to work with it.
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Preview output
Use confirm = FALSE to skip the data preview and confirmation prompt.
File-selection and other informational messages are controlled separately
by suppressMessages(). To import a specified file without headings,
preview output, or informational messages, set RCPA4.verbose = FALSE and
use suppressMessages(getC(file, confirm = FALSE)).
RCPA4 Package Tutorial Videos
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 15.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp. 321-327. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Doing Your Own Political Analysis, Compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
# basic call will prompt user to choose file
if (interactive()) {
getC()
}
Reference information on graphics parameters, like colors, line types, plotting characters
Description
Students can use these functions as quick references on some of R's plotting options.
The Colors function produces plot of colors available in R. Colored cells labels with numeric value that corresponds to that color. No values supplied to function.
The lineType function displays line types for R plots. No values supplied to function.
The plotChar function displays plotting characters available in R. No values supplied to function.
Usage
Colors()
lineType()
plotChar()
Value
No value returned
No value returned
No return
Examples
Colors()
lineType()
plotChar()
GSS 2024 dataset for R Companion to Political Analysis, Fourth Edition
Description
A student-friendly subset of the 2024 General Social Survey. This dataset is used to demonstrate application of R to political analysis. See book Appendix for variable names and descriptions.
Format
A data frame with 3309 rows and 365 variables.
- id
Respondent identification number
- abany
Abortion allowed for any reason
- abdefect
Abortion allowed for serious birth defect
- abhlth
Abortion allowed if woman's health is endangered
- abnomore
Abortion allowed if married woman wants no more children
- abpoor
Abortion allowed if woman cannot afford child
- abrape
Abortion allowed if pregnancy resulted from rape
- absingle
Abortion allowed if woman is not married
- acpttg
People are generally accepting
- adoptus
Immigrants should adopt American culture
- adults
Number of adults age 18 and older in household
- adultsinhh
Total adults in household, experimental version
- affrmact
Favor preferential hiring of Black applicants
- afraidof
Others act afraid of R
- age
R's age in years
- agekdbrn
Age at first child's birth
- amancstr
Importance of American ancestry
- ambetter
Belief that America is a better country
- ambornin
Importance of being born in America
- amchrstn
Importance of being Christian
- amcit
Importance of US citizenship
- amcitizn
Preference for being a US citizen
- amfeel
Importance of feeling American
- amgovt
Importance of respecting US laws
- amownway
America should follow its own interests
- amshamed
Ashamed of some aspects of America
- amtv
Preference for American films on television
- attend
Frequency of attending religious services
- babies
Number of children under age 6 in household
- ballot
Ballot assignment
- befair
People try to take advantage
- belikeus
Better if others were more like Americans
- biasnews
Political news coverage is biased
- bible
View of the Bible
- bizmoney
Business profits come at expense of workers
- born
Born in the United States
- brneffrt
Can become American if born elsewhere
- cantrust
People can be trusted
- cappun
Favor or oppose death penalty for murder
- childs
Number of children
- childsinhh
Total children in household, experimental version
- chldidel
Ideal number of children
- chngdocs
Policy on changing official documents
- citizen
US citizen
- class
Subjective class identification
- cohort
R's birth cohort year
- colath
Allow anti-religionist to teach in college
- colcom
Fire Communist college teacher
- colmslm
Allow anti-American Muslim cleric to teach
- colrac
Allow racist to teach in college
- compuse
Uses a computer
- conarmy
Confidence in military
- conbus
Confidence in major companies
- conclerg
Confidence in organized religion
- coneduc
Confidence in education system
- confed
Confidence in executive branch of federal government
- confinan
Confidence in banks and financial institutions
- coninc
Family income in constant dollars
- conjudge
Confidence in US Supreme Court
- conlabor
Confidence in organized labor
- conlegis
Confidence in Congress
- conmedic
Confidence in medical profession
- conpow
Conflict between ordinary people and elites
- conpress
Confidence in press
- conrinc
R's income, inflation adjusted
- consci
Confidence in scientific community
- conscrp
Importance of military service
- contv
Confidence in television
- corruptn
Perceived corruption in public service
- courts
Courts too harsh or too lenient
- degree
Highest degree earned
- dem10fut
Democracy will work in ten years
- dem10pst
Democracy worked ten years ago
- demtoday
Democracy works today
- denom
Religious denomination
- denom16
Denomination raised in at age 16
- dipged
High school diploma, GED, or equivalent
- discaff
Belief that whites are hurt by affirmative action
- discaffm
Men denied job or promotion due to gender discrimination
- discaffw
Women denied job or promotion due to gender discrimination
- disrspct
R treated with less courtesy or respect
- divlaw
Divorce laws too easy or too difficult
- divorce
Ever divorced or separated
- dsndntpay
Support for reparations for descendants of enslaved people
- dwelown
Owns or rents home
- earnrs
Number of household income earners
- econstat
Current state of the national economy
- educ
Years of schooling completed
- eqwlth
Government should reduce income differences
- evwork
Ever worked for at least one year
- experts
Rely on experts versus ordinary people
- fair
People are fair or take advantage
- famgen
Number of family generations in household
- fear
Afraid to walk alone at night
- fechld
Mother working does not hurt children
- fefam
Man works and woman cares for home
- fehire
Hire and promote women equally
- fejobaff
Preferential hiring of women
- feovrwrk
Family suffers when women work
- fepol
Women not suited for politics
- fepresch
Preschool children suffer if mother works
- finalter
Change in R's financial situation
- finrela
Satisfaction with family income
- forland
Whether foreigners should be allowed to buy land
- form
Split questionnaire form assignment
- fulldem
People, not politicians, should decide
- fund
Religious fundamentalism
- getahead
How people get ahead in life
- god
Confidence in existence of God
- goodlife
Standard of living will improve
- granborn
Number of grandparents born outside US
- grass
Favor or oppose legalizing marijuana
- gunlaw
Favor or oppose gun permits
- hapmar
Happiness of marriage
- happy
General happiness
- health
Self-rated health
- helpblk
Government should aid Black people
- helpful
People are helpful or selfish
- helpnot
Government should do more or less
- helpoth
Importance for children to help others
- helppoor
Government should improve living standard of poor
- helpsick
Government should help pay for medical care
- helpusa
Support for helping worse off people in America
- hhtype1
Household type, condensed
- hispanic
Hispanic origin
- homosex
Same-sex relations right or wrong
- hompop
Total number of people in household
- hrs1
Hours R worked last week
- hunt
R or spouse hunts
- hunt1
R's spouse or partner hunts
- if16who
Vote choice in 2016 counterfactual
- if20who
Vote choice in 2020 counterfactual
- ifwrong
People should support their country
- immameco
Immigrants are good for the economy
- immassim
Immigrants should assimilate
- immcrime
Immigrants increase crime
- immfate
Treatment of undocumented immigrants
- immideas1
Immigrants bring new ideas and cultures
- immjobs
Immigrants take jobs from natives
- immwlfare
Prefer natives over immigrants for benefits
- imports
Support for limiting imports into the United States
- incgap1
Government responsibility to reduce inequality
- income
Total family income
- indus10
Industry code, 2010 classification
- intlincs
International companies harm local business
- jobfind
Could find equally good job
- joblose
Likely to lose job
- kidssol
Children's standard of living compared to R
- knwpatnt
Knows someone seeing mental health professional
- leftrght
Left-right political self-placement
- letdie1
Allow incurable patients to die
- letin1
Number of immigrants allowed into the United States
- letinasn
Support for increasing immigration from Asia
- letinhsp
Support for increasing immigration from Latin America
- libath
Allow anti-religious book in library
- libcom
Allow Communist book in library
- libmslm
Allow anti-American Muslim cleric book in library
- librac
Allow racist book in library
- life
Life exciting or dull
- liveblks
Neighborhood is half Black
- lkelyvot
Likelihood of voting in 2024
- localnum
Number of employees at R's work site
- major1
College major
- marasian
Approve close relative marrying Asian person
- marblk
Approve close relative marrying Black person
- marcohab
Cohabitation status
- marhisp
Approve close relative marrying Hispanic person
- marital
Current marital status
- marsame
Same-sex couples' right to marry
- martype
Marital type classification
- marwht
Approve close relative marrying White person
- meovrwrk
Men harm family when focused too much on work
- mode
Interview mode
- nataid
Federal spending on foreign aid
- natarms
Federal spending on military and defense
- natchld
Federal spending on childcare assistance
- natcity
Federal spending on solving problems of big cities
- natcrime
Federal spending on halting rising crime
- natdrug
Federal spending on dealing with drug addiction
- nateduc
Federal spending on improving education system
- natenrgy
Federal spending on developing alternative energy
- natenvir
Federal spending on protecting the environment
- natfare
Federal spending on welfare
- natheal
Federal spending on protecting national health
- natrace
Federal spending on improving conditions of Black people
- natroad
Federal spending on highways and bridges
- natsci
Federal spending on scientific research
- natsoc
Federal spending on Social Security
- natspac
Federal spending on space exploration
- news
Frequency of reading newspaper
- noathome
Missed family occasion for work
- nonurse
Unable to care for sick child or relative
- norelgsp
No religion identification
- notsmart
R treated as not smart
- obey
Importance for children to be obedient
- obeylaws
Importance of always obeying laws
- occ10
Census occupation code, 2010 classification
- oppsegov
Importance of civil disobedience
- othlang
Speaks language other than English or Spanish
- othlang1
Other language spoken, first response
- owndecns
Each nation should have its own country
- owngun
Has gun in home
- parborn
Whether parents were born in United States
- parsol
Living standard compared to parents
- partfull
Works full time or part time
- partyid
Political party affiliation
- paytaxes
Importance of never evading taxes
- phone
Has telephone
- pillok
Birth control for teenagers age 14 to 16
- pistol
Pistol or revolver in home
- polabuse
Approve police verbal abuse
- polattak
Approve police physical attack
- poleff11
R has no say in government
- poleff18
Government does not care what people think
- polescap
Approve police preventing escape
- polhitok
Approve police striking suspect
- polintrst
Interest in election campaigns
- polmurdr
Approve police questioning murder suspect
- polnews
Use media for political news
- polopts
Importance of citizen participation
- poltalk
Politicians talk too much
- polviews
Liberal-conservative self-placement
- poorserv
R received poorer service in stores or restaurants
- popular
Importance for children to be popular
- pornlaw
Pornography laws
- posslq
Has marital partner
- postlife
Belief in life after death
- pray
Frequency of prayer
- prayer
Bible prayer in public schools
- premarsx
Sex before marriage
- pres16
Presidential vote recall, 2016
- pres20
Presidential vote recall, 2020
- prestg10
Occupational prestige score, 2010
- prestg105plus
Occupational prestige score, threshold method, 2010
- preteen
Number of children age 6 to 12 in household
- proudart
Pride in American arts and literature
- prouddem
Pride in how American democracy works
- proudeco
Pride in American economic achievements
- proudhis
Pride in American history
- proudpol
Pride in American political influence worldwide
- proudspt
Pride in American achievements in sports
- racdif1
Black-white inequality due to discrimination
- racdif2
Black-white inequality due to inborn ability
- racdif3
Black-white inequality due to lack of education
- racdif4
Black-white inequality due to lack of effort
- racdif5
Black-white inequality due to upbringing
- race
R's race
- raclive
Opposite race in neighborhood
- racopen
Support for open housing law
- rank
Self-ranking in society
- ratechall124
Donald Trump feeling rating
- ratechall1ts
Challenger one time-series rating
- ratechall224
Kamala Harris feeling rating
- ratechall2ts
Challenger two time-series rating
- ratechall324
Nikki Haley feeling rating
- ratechall3ts
Challenger three time-series rating
- ratedemp
Democratic Party feeling rating
- rateincumb24
Joe Biden feeling rating
- rateincumbts
Incumbent time-series rating
- ratemaga
MAGA Republicans feeling rating
- raterepp
Republican Party feeling rating
- realinc
Family income in constant dollars
- realrinc
R's income in constant dollars
- reborn
Born again experience
- refmorwk
Would take additional paid work
- refpromo
Would refuse job promotion
- region
Region of interview
- relactiv
Participation in religious activities
- relig
Religious preference
- religinf
Religion has too much influence in politics
- reliten
Strength of religious affiliation
- relpersn
Self-identified as religious person
- reltrad
Religious tradition classification
- rghtsmin
Government should protect minority rights
- richwork
If rich, would continue working
- rifle
Rifle in home
- rincome
R's income
- rowngun
Gun belongs to R
- rplace
R's relationship to household head
- satdemoc
Satisfaction with democracy in America
- satfin
Satisfaction with financial situation
- satjob
Satisfaction with job
- sei10
Occupational socioeconomic index, 2010
- sei10educ
Percent with some college in R's occupation
- sei10inc
Percent with high income in R's occupation
- servpub
Public service serves people
- sex
R's sex
- sexbirth1
Sex assigned at birth
- sexeduc
Sex education in public schools
- sexnow2
Current gender identity
- sexornt
Self-identified sexual orientation
- shotgun
Shotgun in home
- sibs
Number of siblings
- smedia
Impact of social media exposure
- socbar
Evening at bar
- socfrend
Evening with friends
- socommun
Evening with neighbors
- socrel
Evening with relatives
- solok
Importance of adequate standard of living
- spaneng
Interview conducted in Spanish or English
- spanking
Favor spanking
- spkath
Allow anti-religionist to speak
- spkcom
Allow Communist to speak
- spklang
How well R speaks other language
- spkmslm
Allow Muslim cleric preaching hatred to speak
- spkrac
Allow racist to speak
- suicide1
Suicide if incurable disease
- suicide2
Suicide if bankrupt
- suicide4
Suicide if tired of living
- svyenjoy
Enjoy taking surveys
- tax
Federal income tax
- teens
Number of children age 13 to 17 in household
- teensex
Teen sex age 14 to 16
- thnkself
Importance for children to think for themselves
- threaten
R threatened or harassed
- trust
People can be trusted
- tvhours
Hours watching television per day
- unemp
Unemployed in last ten years
- union
R or spouse is a labor union member
- union1
R's spouse or partner is a labor union member
- unrelat
Number of unrelated people in household
- usmca1
Familiarity with USMCA
- usmca2
Belief that United States benefits from USMCA
- vetyears
Years R served in the armed forces
- visitors
Number of visitors in household
- vote16
Voted in 2016 election
- vote20
Voted in 2020 election
- voteprob
Voting problems in US elections
- watchgov
Importance of keeping watch on government
- weekswrk
Weeks R worked last year
- whovote24
Presidential vote intention, 2024 pre July 25
- whovote24a
Presidential vote intention, 2024 post July 25
- whovotets
Presidential vote intention, time series
- widowed
Ever widowed
- wlthblks
Stereotype of Blacks as rich or poor
- wlthhsps
Stereotype of Hispanics as rich or poor
- wlthwhts
Stereotype of whites as rich or poor
- wordsum
Vocabulary test score
- workblks
Stereotype of Blacks as hard working or lazy
- workhard
Importance for children to work hard
- workhsps
Stereotype of Hispanics as hard working or lazy
- workless
Cut back on work
- workwhts
Stereotype of whites as hard working or lazy
- wrkgovt1
R works for government
- wrkgovt2
R works for a private employer
- wrkslf
Self-employed or works for someone else
- wrkstat
Labor force status
- wrkwayup
Belief that Blacks can overcome prejudice without favors
- wrldgovt
International bodies should enforce environmental rules
- wtssnrps
Post-stratification weight, adjusted
- wtssps
Post-stratification weight
- xmarsex
Sex with someone other than spouse
- xmovie
Watched adult movie last year
- xnorcsiz
Expanded NORC size code
- volunteer_assign
Volunteer response assignment
- ab_index
Number of abortion-access circumstances supported, 0 to 7
- suicide_index
Number of circumstances where person has right to suicide, 0 to 3
- natspend_index
Support for national spending index, -17 to +17
- social_index
Social activity index, 0 to 24
- police_force_index
Number of circumstances justifying police striking citizen, 0 to 5
- discrim_exp_index
Discrimination experience index, 0 to 25
- con_inst_index
Confidence in institutions index, 0 to 26
- speech_tol_index
Free speech tolerance index, 0 to 12
- partyid7
Political party affiliation, 7 categories
- partyid3
Political party affiliation, 3 categories
Source
General Social Survey, 2024. See Appendix of printed textbook for further information.
Interactive helper for RCPA4 documentation, examples, resources, plotting references, and settings
Description
Opens an interactive menu with these top-level options:
-
Show help file for RCPA4 function. Select a core RCPA4 function and display its help file.
-
Explore RCPA4 datasets and variables. Select an RCPA4 dataset, display its help file, and browse its variables.
-
Show an example. Select a core RCPA4 function and run its documented example.
-
Help with plots. Open color, line-type, and plotting-character references, or check graphics support.
-
Find data. Browse datasets in installed packages or open online sources of political data.
-
Change RCPA4 package settings. Adjust
RCPA4.verbose,RCPA4.slow, andRCPA4.pause_seconds. -
Clean working environment. List workspace objects and show commands users can run themselves to remove one, several, or all non-hidden objects.
-
Reset graphical parameters. Close the active graphics device so later plots use default settings.
-
Browse chapter resources. Open the supplemental web resources for Getting Started, Chapters 1-15, or Advanced Topics.
Usage
helpC(option = NULL)
Arguments
option |
(Optional) A top-level menu choice from |
Value
Invisibly returns NULL.
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Interactive menu output
The settings menu at helpC(6) displays effective session preferences,
using package defaults for unset options. Viewing and exiting the menu does
not change options. Preferences change only when you select a settings action.
The helpC() menu and prompts remain visible when RCPA4.verbose = FALSE.
Result-table controls are documented separately in each analysis function's
help page.
Workspace cleanup
Option 7 lists non-hidden objects in the global environment and displays
rm(object_name), rm(obj1_name, obj2_name), and rm(list = ls()) as commands
to run at the R console. Replace the placeholder names with your object names.
rm(list = ls()) removes all non-hidden objects in the current environment.
The menu itself does not remove or modify any workspace objects.
Loading installed datasets
In option 5, the installed-package dataset browser displays dataset help
and a utils::data() command to run at the R console. The browser does not
load the selected dataset or modify workspace objects. For entries such as
beaver1 (beavers), the command uses the dataset name in parentheses.
Examples
if(interactive()){
helpC()
helpC(5)
}
Creates histogram to show distribution of interval (numeric) variable's values
Description
Generates frequency distribution table of binned values and a histogram to describe distribution of variable values.
Usage
histC(x, w = NULL, data = NULL, breaks = "Sturges", digits = 2,
printC = FALSE, plot = TRUE, main = NULL, xlab = NULL,
ylab = "Frequency", bar.col = "gray80", table = TRUE, ...)
Arguments
x |
The variable to be analyzed. If dataset not specified with data argument, should be a vector in form dataset$var. |
w |
(Optional) Sample weights (must be numeric if used), If dataset not specified with data argument, should be in form dataset$weighvar |
data |
(Optional) Name of dataset that contains x (and w) variable. |
breaks |
(Optional) Specify how to break the x variable into bins. Options include the number of breaks, a vector specifying the breakpoints, or the name of an algorithm that generates breakpoints. Default value is "Sturges" (other algorithms are "Scott" and "FD"). |
digits |
(Optional) Number of digits to display after decimal points (default is 2). |
printC |
(Optional) Do you want the histogram and binned frequencies table printed to working directory? (default: FALSE) |
plot |
(Optional) Do you want the histogram graphic? (default: TRUE) |
main |
(Optional) Customize main title for histogram. |
xlab |
(Optional) Custom label for x-axis of histogram. |
ylab |
(Optional) Custom label for y-axis of histogram. |
bar.col |
(Optional) Color for histogram bars; default is "gray80". |
table |
(Optional) Do you want the binned frequency table reported? (default: TRUE) |
... |
(Optional) Additional arguments passed to the internal wtd histogram helper. |
Value
A frequency distribution table of binned x variable values.
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
Table and plot requirements
At least one of table or plot must be enabled. When using table = FALSE,
keep a valid plot enabled.
RCPA4 Package Tutorial Videos
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 2.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp. 39-55. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Descriptive Statistics, Compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
histC(x=states$covid_cases_per1000)
Converts linear predictor to probability
Description
Calculates predicted probability for a given logged odds value. This function calculates predicted probability for a given logged odds value, often useful for plotting or reporting predicted probabilities.
Usage
inverse_logit(logged_odds)
Arguments
logged_odds |
A numeric value, or vector of numeric values. |
Value
Returns predicted probability corresponding the the logged odds value, a numeric value between 0 and 1.
Examples
library(RCPA4)
inverse_logit(0)
inverse_logit(-5:5)
Calculates Lambda, a measure of association for a cross-tabulation.
Description
Given a table of conditional frequencies, the lambda function calculates and returns Lambda, a measure of association between two categorical variables (factors). Lambda is equal to the proportion of errors reduced by knowledge of the independent variable.
Usage
lambda(tab, digits = 3, detailed = FALSE)
Arguments
tab |
The conditional frequencies of a cross-tabulation. The dependent variable should correspond to rows and the independent variable, to columns. |
digits |
Number of decimal places of Lambda reported (defaults to 3). |
detailed |
Do you want detailed report on how lambda value calculated? (default is FALSE). |
Value
Returns the value of Lambda.
Examples
library(RCPA4)
conditional.frequencies <- table(dv=states$lgbtq_equality_5cat, iv=states$religiosity_3cat)
lambda(tab=conditional.frequencies, detailed=TRUE)
Logistic regression analysis with options for weighted observations, odds ratio reports, model fit statistics, and plots of residuals
Description
Logistic regression analysis function with many useful features. Its standard output includes a table of coefficients, table of deviance residuals, and table of estimation information. Options include weighting observations, additional reports on odds ratios, ANOVA, classification table, multiple measures of model fit (including Lambda PRE), and diagnostic plots of residuals.
Usage
logregC(formula, w = NULL, data = NULL, digits = 3, orci = FALSE,
fit.stats = FALSE, anova = FALSE, classify = FALSE, printC = FALSE,
plot.res = FALSE, table = TRUE, simple.factors = TRUE, ...)
Arguments
formula |
should be in dataset$dv ~ datatset$iv1 + dataset$iv2 unless dataset specified in optional data argument. |
w |
(Optional) Sampling weights of variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains dv, iv (and w) variables. |
digits |
(Optional) Number of decimal places reported in result (defaults to 3). |
orci |
(Optional) Do you want table reporting odds ratios for coefficients with confidence intervals? (default: FALSE) |
fit.stats |
(Optional) Do you want a table of assorted model fit statistics? (default: FALSE) |
anova |
(Optional) Do you want ANOVA table reported? (default: FALSE) |
classify |
(Optional) Do you want a classification table (observed vs predicted outcomes)? (default: FALSE) |
printC |
(Optional) Do you want results printed to .html file in your working directory? Default is FALSE. Set to TRUE to print results. |
plot.res |
(Optional) Do you want a set of diagnostic plots of model residuals? (default: FALSE) |
table |
(Optional) Do you want logistic regression result tables reported? (default: TRUE) |
simple.factors |
(Optional) Treat ordered factors like regular factors in regression models? Default is TRUE. Set to FALSE to use R's current contrast setting for ordered factors. |
... |
(Optional) Additional arguments passed to |
Value
Returns an augmented glm (unweighted models) or svyglm (weighted models)
object. The primary model object is unchanged for standard methods (for example
predict, coef, summary), and auxiliary result tables are available via
[[ (for example fit[["model_fit_table"]]).
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
RCPA4 Package Tutorial Videos
-
Logistic Regression Analysis with RCPA4 Package's logregC Function 13:36
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 14.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), Chapter 9. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Logistic Regression, compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
# basic usage with variable vectors
logregC(states$battleground2020 ~ states$vep20_turnout)
# with post-estimation analysis
logregC(states$battleground2020 ~ states$vep20_turnout, orci=TRUE, fit.stats=TRUE,
anova=TRUE, classify=TRUE, plot.res=TRUE)
logregC(anes$has_children=="Yes" ~ anes$gender_s_sex + anes$r_age_election_day,
w=anes$wt)
Logistic regression model fit statistics
Description
Logistic regression model statistics, reported by logregC with fit.stats=TRUE argument, can be used for both weighted and unweighted logregC models.
Usage
logregR2(model, digits = 3)
Arguments
model |
An estimated logistic regression model (a glm or svyglm object) |
digits |
Number of digits to be displayed after decimal points |
Value
Returns list of statistics about model (a "LogRegR2" class object)
Examples
library(RCPA4)
logit.model <- logregC(states$battleground2020 ~ states$vep20_turnout)
logregR2(logit.model)
Translate logistic regression coefficients into odds ratios with confidence interval
Description
Generates odds-ratios based on logistic regression model coefficients, reported by logregC with orci=TRUE argument
Usage
orci(model, digits = 3)
Arguments
model |
An estimated logistic regression model |
digits |
Number of digits after decimal to display |
Value
Returns odds rations and confidence intervals in columns (a matrix class object)
Examples
library(RCPA4)
logit.model <- logregC(states$battleground2020 ~ states$vep20_turnout)
orci(logit.model)
Compares full v. reduced logistic regression models with Chi-Squared test
Description
Compares full and reduced logistic regression models with Chi-Square Test to assess whether additional variables of full model are statistically significant.
Usage
pchisqC(reduced, full, digits = 3)
Arguments
reduced |
The reduced logistic regression model as an object. This is model with fewer independent variables. |
full |
The full logistic regression model as an object. This is model with more independent variables. |
digits |
(Optional) The number of digits to display after decimal point, default is 3. |
Value
A formatted result object with the chi-squared statistic, df, and P-value to test the null hypothesis that the full model is no better than the reduced model.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 14.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), Chapter 9. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Examples
library(RCPA4)
model_full <- logregC(battleground2020 ~ vep20_turnout + adv_or_more, data=states)
model_reduced <- logregC(battleground2020 ~ vep20_turnout, data=states)
pchisqC(reduced=model_reduced, full=model_full)
Prints table of results to a .html file in local working directory
Description
Prints table or summary of results to a .html file in local
working directory. Converting Console format tables to .html tables helps
users quickly create publication- and presentation-ready tables. The .html
file's name is displayed as Console message.
Current date added to Table.Output.html file name to keep output organized.
You can print output directly from Companion functions using printC=TRUE
argument (where available).
Usage
printC(objx, file = NULL)
Arguments
objx |
A table or data frame. The table must be html-ready, not all
Console output is organized in tables. If objx is not a html-ready table,
|
file |
(Optional) The path/file name for .html output. If not specified, function will output to .html file in your working directory. |
Value
Invisibly returns append metadata used by internal block printers. The formatted objx is outputted to a .html file in working directory.
RCPA4 Package Tutorial Videos
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook Reference
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 1.
Examples
library(RCPA4)
example.table <- freqC(x=world$vdem_4cat, plot=FALSE)
# running printC will generate a .html file in your working directory
printC(example.table, file=tempfile(fileext = ".html"))
Backward-compatible alias for random_names().
Description
Backward-compatible alias for random_names().
Usage
random.names(n)
Arguments
n |
The number of random surnames to be generated. |
Value
A vector of surnames.
Generates random sample of nationally representative surnames
Description
Generates a random sample of surnames of any length. Surnames and probabilities from Census Bureau, see <https://www.census.gov/topics/population/genealogy/data/2010_surnames.html>. Used to illustrate random sampling methods.
Usage
random_names(n)
Arguments
n |
The number of random surnames to be generated |
Value
A vector of surnames
RCPA4 Package Tutorial Videos
* [Complete Playlist of RCPA4 Package Tutorial Videos](https://www.youtube.com/playlist?list=PL3jY4WDTUxoNqrxSSQH4q7XPLPYipeNCu), includes video for this function and many more.
Examples
library(RCPA4)
random_names(10)
Linear regression analysis (OLS regression), with options for weighted observations, diagnostic tests, and plots of residuals
Description
Linear regression analysis function with many useful features. Standard output of results includes table of coefficients, table of residuals, and additional model information. Options for weighting observations, analysis of variance (ANOVA), performing post-estimation diagnostic tests, including testing normality of residuals and constant variance, and generating diagnostic plots of residuals.
Usage
regC(formula, w = NULL, data = NULL, digits = 3, anova = FALSE,
norm.test = FALSE, ncv.test = FALSE, linear.test = FALSE,
reset.test = FALSE, outlier.test = FALSE, vif = FALSE,
printC = FALSE, plot.res = FALSE, table = TRUE,
simple.factors = TRUE, ...)
Arguments
formula |
should be in dataset$dv ~ datatset$iv1 + dataset$iv2 unless dataset specified in optional data argument. If weights are specified using w argument, the formula cannot contain functions or logical statements (all variables in the function must be named in the dataset). |
w |
(Optional) Sampling weights of variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains dv, iv (and w) variables. |
digits |
(Optional) Number of decimal places reported in result (defaults to 3). |
anova |
(Optional) Do you want ANOVA table reporting F-test for all predictors? (default: FALSE) |
norm.test |
(Optional) Test assumption that regression residuals follow normal distribution (default: FALSE) |
ncv.test |
(Optional) Test assumption that regression residuals have constant variance (default: FALSE) |
linear.test |
(Optional) Report results of linearity test? (default: FALSE) |
reset.test |
(Optional) Report results of model specification test? (default: FALSE) |
outlier.test |
(Optional) Test whether outlier observations have outsized leverage on results (default: FALSE) |
vif |
(Optional) Report variance inflation factors to assess multicollinearity? (default: FALSE) |
printC |
(Optional) Do you want to print tables of results (and residuals plots if plot.res=TRUE) to .html file in working directory? (default: FALSE) |
plot.res |
(Optional) |
table |
(Optional) Do you want regression result tables reported? (default: TRUE) |
simple.factors |
(Optional) Treat ordered factors like regular factors in regression models? Default is TRUE. Set to FALSE to use R's current contrast setting for ordered factors. |
... |
(Optional) Additional arguments passed to |
Value
Returns an augmented lm or svyglm object. The primary model object is
unchanged for standard methods (for example residuals, coef, predict),
and auxiliary result tables are available via [[ (for example
fit[["model_fit_table"]]).
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
RCPA4 Package Tutorial Videos
-
Bivariate Regression Analysis with RCPA4 Package's regC Function 10:31
-
Multiple Regression Analysis with RCPA4 Package's regC Function 14:55
-
Analyzing Regression Residuals with RCPA4 Package's regC Function 12:41
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapters 11, 12, 13.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp. 244-271. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Correlation and Bivariate Regression, Multiple Regression, and Analyzing Regression Residuals, compiled by Barry C. Edwards.
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
# basic usage
regC(states$vep20_turnout ~ states$hs_or_more)
# with w and data arguments
regC(anes$ft_labor_unions ~ anes$ft_dem_party, w=anes$wt)
# multiple IV with some post-estimation tests
regC(peace_index ~ vdem_edi_score + hdi, data=world, norm.test=TRUE, ncv.test=TRUE)
Plots probability and cumulative density functions (PDFs and CDFs) of sample statistics
Description
Visualize expected sampling distributions for sample statistics. You can plot the probability and cumulative density functions for statistics based on either the normal distribution or a t-distribution.
The sampdistC function also generates the confidence interval (default 95%) for a sample statistic which is useful for obtaining the CI of a summary statistic (when you're not estimating it from the dataset yourself).
Usage
sampdistC(stat, se, t.df = NULL, plot.cdf = FALSE, ci = 95, digits = 3,
printC = FALSE, table = TRUE)
Arguments
stat |
A numeric statistic, the point estimate of a parameter based on a sample of observations, like a sample mean or a sample proportion. |
se |
The standard error of the statistic, must be a positive number. |
t.df |
(Optional) If critical values for sampling distribution should be based on t-distribution (generally true when statistic is a mean), set t.df to the number of degrees of freedom (typically n-1). |
plot.cdf |
(Optional) Do you want to plot the cumulative density function? Default = FALSE (for probability density function). |
ci |
(Optional) Specify desired confidence level for confidence interval as a percentage. Set ci=FALSE to suppress CI table (default: 95) |
digits |
(Optional) Number of digits after decimal to display in CI table (default: 3) |
printC |
(Optional) Do you want to sampling distribution plot to .html file in working directory? (default: FALSE) |
table |
(Optional) Do you want the confidence interval table reported when |
Value
Invisibly returns a data frame (sampdistC_result) containing the CI table
when ci is requested. If ci=FALSE, returns an empty CI-shaped data frame and
stores ci_table=NULL in auxiliary metadata.
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
RCPA4 Package Tutorial Videos
-
Viewing Sampling Distributions with RCPA4's sampdistC Function 21:51
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 8.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), Chapter 6. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Foundations of Inference, Compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
sampdistC(stat=10, se=1)
# based on normal distributions
sampdistC(stat=10, se=1, plot.cdf=TRUE)
# based on t-distribution with 15 degrees of freedom
sampdistC(stat=8, se=2, t.df=15)
sampdistC(stat=8, se=2, t.df=15, plot.cdf=TRUE)
Sorts dataset observations by user-defined criteria to return case-level information
Description
Returns case-level information in order specified by user. You can sort by additional criteria to break ties. Useful for learning about units of analysis and selecting cases for qualitative research designs.
Usage
sortC(id, by, data = NULL, thenby = NULL, descending = TRUE,
limit = NULL, digits = 3, confirm = TRUE, printC = FALSE,
table = TRUE)
Arguments
id |
A variable in the dataset (data) that identfies individual cases, typically the name of states, countries, etc. |
by |
Variable the cases should be sorted by. |
data |
(Optional) Dataset to be sorted. |
thenby |
(Optional) Criteria for sorting cases after sorting with the "by" variable. Useful if many cases tied on first criteria. |
descending |
(Optional) Should the cases be sorted in descending order? By default, set to TRUE. When sorting ordered factors, check that the levels higher numerically correspond to the sort order you have in mind. |
limit |
(Optional) The number of rows to report. If there are many observations to be sorted, you may want to limit output to 5, 10, etc. rows. |
digits |
(Optional) Number of decimal places reported in result (default: 3). |
confirm |
(Optional) If function is going to return long table of results (more than 20 rows), you'll be asked for confirmation (use |
printC |
(Optional) Do you want to print table of sorted observations to to .html file in working directory? (default: FALSE) |
table |
(Optional) Display the sorted-observations table? Defaults to
|
Value
Invisibly returns a data frame of sorted observations, limited to
limit rows when supplied, including when table = FALSE. Assign the
function call to an object to store the results.
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
Returning results without display
With table = FALSE, the table and its heading are omitted, the long-table
confirmation prompt is skipped, and no HTML output is written, even if
printC = TRUE. The limit argument still controls the number of rows
returned. With table = TRUE, use confirm = FALSE to bypass confirmation
for a long table. Informational messages remain controlled separately by
suppressMessages().
RCPA4 Package Tutorial Videos
-
Sort and View Case-Level Information with the sortC Function 12:22
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapters 2, 6.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp. 122-123. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Descriptive Statistics, compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
# basic usage
sortC(id=states$state, by=states$volunteer_hrs_pc, limit=10, confirm=FALSE)
# store sorted results without displaying the table
sorted <- sortC(id=states$state, by=states$volunteer_hrs_pc, table=FALSE)
# options to limit results and sort in ascending order
sortC(id=country, by=gini_index, descending=FALSE, limit=10, data=world)
# sort by and thenby
sortC(id=country, by=vdem_4cat, thenby=gini_index, descending=c(FALSE, FALSE),
data=world, confirm=FALSE)
sortC(id=country, by=vdem_4cat, thenby=gini_index, descending=c(FALSE, TRUE),
data=world, confirm=FALSE)
States dataset for R Companion to Political Analysis, Fourth Edition
Description
A dataset with variables about the 50 states. This dataset is used to demonstrate application of R to political analysis. See book Appendix for variable names and descriptions.
Format
A data frame with 50 rows and 186 variables.
- abortion_ban
Total abortion ban according to Guttmacher Institute as of July 1, 2026 (1 = yes, 0 = no)
- abortion_legal
Percentage saying abortion should be legal in all or most cases (PRRI 2025)
- abortion_rate
Abortion rate per 1,000 women ages 15-44 (2025)
- abortlaws_7cat
Level of abortion restriction or protection by state (Guttmacher Institute, as of July 1, 2026)
- adv_or_more
Percentage age 25 or older with a graduate or professional degree (2024 ACS, table B15003)
- alcohol
Apparent alcohol consumption in gallons of ethanol per resident age 14 or older (2023)
- assault_ban_support
Percentage supporting a ban on assault-style rifles (CES 2024)
- attend_weekly
Percentage attending religious services weekly or more (PRRI 2025)
- ba_or_more
Percentage age 25 or older with at least a bachelor's degree (2024 ACS, table B15003)
- ballots24_total
Total ballots counted in the 2024 general election (UF Election Lab)
- battleground2020
Battleground in 2020? (Cook Political Report)
- battleground2024
Presidential battleground state in 2024 (Ballotpedia; 1 = yes, 0 = no)
- biden2020
Biden two-party vote percentage in 2020 election
- black_percent
Percentage Black alone and not Hispanic or Latino (2024 ACS, table B03002)
- broadband
Percentage of households with a broadband internet subscription of any type (2024 ACS, table B28002)
- carfatal
Motor-vehicle traffic fatalities per 100,000 population (2024)
- carry_easier_support
Percentage supporting making concealed carry easier (CES 2024)
- cellular_only
Percentage of households with only a cellular data internet subscription (2024 ACS, table B28002)
- charitable_giving_pc
Tax-reported charitable contributions per resident (2022)
- christian_dominion
Agreement that Christians should exercise dominion over U.S. society (percent; PRRI 2025)
- christian_foundations
Agreement that America depends on its Christian foundations (percent; PRRI 2025)
- christian_identity
Percentage agreeing being Christian is an important part of being truly American (PRRI 2025)
- christian_laws
Percentage agreeing U.S. laws should be based on Christian values (PRRI 2025)
- christian_nation
Percentage agreeing the U.S. government should declare America a Christian nation (PRRI 2025)
- cig_tax
State cigarette excise tax per pack (July 1, 2025)
- cig_tax_3cat
State cigarette excise tax category based on July 1, 2025 KFF rates
- cigarettes
Packs smoked bimonthly per adult (2003)
- climate_policies
Number of state climate policies enacted (State Climate Policy Dashboard snapshot, July 10, 2026)
- cn_support
Percentage classified as Christian nationalism Adherents or Sympathizers (PRRI 2025)
- cong119_demshare
Democratic percentage of state's 119th Congress delegation at opening (2025)
- cook_pvi_scores
Cook PVI score (2025; positive = Republican)
- corporal_punishment_banned
Corporal punishment prohibited in public schools (November 2024; 1 = yes, 0 = no)
- corrections_incarc_rate
Incarcerated population per 100,000 residents (2024)
- corrections_total_rate
Population under correctional control per 100,000 residents (2026)
- covid_cases_per1000
Cumulative reported COVID-19 cases per 1,000 population through May 10, 2023
- covid_deaths_per1000
Cumulative reported COVID-19 deaths per 1,000 population through May 10, 2023
- covid_response_max
Maximum COVID-19 response stringency index (2020-21)
- covid_response_mean
Mean COVID-19 response stringency index (2020-21)
- covid_vaccinated
Percentage completing the original COVID-19 primary vaccination series (May 10, 2023)
- crime_rate_burglary
Burglary offenses per 100,000 residents (FBI via USAFacts, 2024)
- crime_rate_murder
Murder and non-negligent manslaughter offenses per 100,000 residents (FBI via USAFacts, 2024)
- crime_rate_overall
Violent plus property crime offenses per 100,000 residents (FBI via USAFacts, 2024)
- crime_rate_property
Property crime offenses per 100,000 residents (FBI via USAFacts, 2024)
- crime_rate_violent
Violent crime offenses per 100,000 residents (FBI via USAFacts, 2024)
- deathpen_status
Does state retain the death penalty? Current as of 2025. From Death Penalty Information Center
- defense_expend
Federal defense expenditures per capita (FY2024)
- democracy_5cat
Five-category MAP Democracy Overall Policy classification (December 1, 2025)
- democracy_score
MAP Democracy Overall Policy Score (December 1, 2025)
- density
Population per square mile (2024 ACS B01001; 2020 Census TIGER/Line)
- diabetes_death_rate
Diabetes death rate per 100,000 population (KFF State Health Facts, 2024)
- direct_democracy_tools
Number of statewide direct-democracy tools available (2025)
- division
Census division (9 different regions of country)
- drug_death_rate
Age-adjusted drug overdose deaths per 100,000 residents (2024)
- dv_survivor_protections
Employment protections for domestic-violence survivors (0-4; 2024)
- earmarks_pcap
Federal earmarks per capita (FY2026)
- energy_efficiency_score
ACEEE state energy-efficiency score (2025)
- fairpoor_health
Adults reporting fair or poor health (percent; 2024)
- felon_ineligible24
People ineligible to vote because of felony rules (2024)
- firearm_death_rate
Firearm death rate per 100,000 population (KFF State Health Facts, 2024)
- foreign_born
Percentage born outside the United States (2024 ACS, table B05012)
- giffords_grade
GIFFORDS gun law strength letter grade (2025)
- giffords_rank
GIFFORDS gun law strength rank (2025; 1 = strongest laws)
- gini
Gini index of income inequality (2024 ACS, table B19083)
- government_workers
Percentage of employed civilians working for local, state, or federal government (2024 ACS)
- governor_party
Governor's party: D = Democratic or R = Republican (NCSL 2026)
- gun_dealers
Active firearm dealers per 100,000 residents (March 2026)
- gun_deaths_100k
Age-adjusted firearm death rate per 100,000 population (2024)
- gun_law_strength
Everytown Gun Law Strength score (2026)
- gun_murders
Age-adjusted firearm homicide death rate per 100,000 population (2024)
- gun_ownership
Estimated percentage of adults living in a household with a firearm (2016)
- gunsammo_rank
Ammo.com ranking of states for gun owners (2026; 1 = most gun-friendly)
- harris2024
Kamala Harris two-party vote percentage in 2024 election
- hh_income
Median household income in 2024 inflation-adjusted dollars (2024 ACS, table B19013)
- hispanic_percent
Percentage Hispanic or Latino of any race (2024 ACS, table B03002)
- homeless_per_10k
People experiencing homelessness per 10,000 residents (January 2024)
- homeownership
Percentage of occupied housing units that are owner-occupied (2024 ACS, table B25003)
- homeschool_percent
Percentage of K-12 students homeschooled (2023-24 estimate)
- hs_or_more
Adults age 25+ with a high school credential (percent; 2024)
- income_percapita
Per capita income in 2024 inflation-adjusted dollars
- infant_mortality
Infant deaths per 1,000 live births (KFF State Health Facts, 2023 vital statistics; Vermont 2022)
- judge_selection
Primary method for selecting justices of the state's court of last resort (2026)
- judges_elected
State high-court justices selected by contested election (1 = yes)
- labor_force_percent
Percentage age 16 or older in the labor force (2024 ACS, table B23025)
- land_area
State land area in square miles (2020 Census TIGER/Line state boundaries)
- leg_dem_seats
Total Democratic legislative seats across both chambers (NCSL 2026 partisan composition)
- leg_other_seats
Other-party or nonpartisan legislative seats (2026)
- leg_rep_seats
Total Republican legislative seats across both chambers (NCSL 2026 partisan composition)
- lgbtq_equality_5cat
Five-category MAP LGBTQ Equality Overall Policy classification (December 1, 2025)
- lgbtq_equality_score
MAP LGBTQ Equality Overall Policy Score (December 1, 2025)
- lgbtq_nondiscrim
Percentage favoring laws protecting LGBTQ people from discrimination (PRRI 2025)
- life_expectancy
Life expectancy at birth in years (KFF State Health Facts using NCHS state life tables, 2022)
- marijuana_legal_status
State marijuana legal status (2025-2026)
- median_age
Median age of the state population (2024 ACS, table B01002)
- median_gross_rent
Median monthly gross rent in dollars (2024 ACS, table B25064)
- median_home_value
Median value of owner-occupied housing units in dollars (2024 ACS, table B25077)
- medicaid_expansion
State adopted ACA Medicaid expansion (1 = adopted, 0 = not adopted; KFF tracker, May 2026)
- minimum_wage
State minimum wage as of July 1, 2026
- ncaj_attorney_access
NCAJ Attorney Access Index score (2021)
- ncaj_consumer_debt
NCAJ Consumer Debt Litigation Index score (2024)
- ncaj_disability_access
NCAJ Disability Access Index score (2021)
- ncaj_fines_fees
NCAJ Fines and Fees Index score (2022)
- ncaj_justice_index
National Center for Access to Justice overall Justice Index score (updated 2024)
- ncaj_language_access
NCAJ Language Access Index score (2021)
- ncaj_self_representation
NCAJ Self-Representation Access Index score (2021)
- no_internet
Percentage of households with no internet access (2024 ACS, table B28002)
- noncitizen24
Estimated percentage of the voting-age population that is noncitizen in 2024 (UF Election Lab)
- obesity_percent
Percentage of adults with BMI of 30 or higher (KFF State Health Facts, 2024 BRFSS; Tennessee 2023)
- online_gambling
Legal online gambling type (July 2026)
- online_gambling_legal
Percentage saying online gambling should be legal in all or most cases (PRRI 2025)
- opioid_rx_rate
Retail opioid prescriptions dispensed per 100 persons (2024)
- over64
Percentage of the population age 65 or older (2024 ACS, table B01001)
- pop_18_24
Percentage of the population ages 18 through 24 (2024 ACS, table B01001)
- pop_18_44
Percentage of the population ages 18 through 44 (2024 ACS, table B01001)
- population
Total state population (2024 ACS, table B01001)
- population_change
Percentage increase/decrease in population from 2010 to 2020 (not annualized)
- pot_policy
Marijuana laws (as of June 2021). From the National Conference of State Legislatures
- poverty_rate
Percentage below the poverty level in the past 12 months (2024 ACS, table B17001)
- preg_uninten_rate
Unintended pregnancy rate per 1,000 women 15-44 (2010). From Guttmacher Institute
- private_choice_programs
Number of private-school-choice program types present (2024; 0-3)
- prochoice_percent
Adults saying abortion should be legal in all or most cases (percent; 2023-24)
- protect_immigrants
Protection of immigrants: ILRC immigration-enforcement score (2024)
- public_transit
Workers commuting by public transportation (percent; 2024)
- region
Census region (4 categories)
- relig_import
Adults saying religion is very important in their lives (percent; 2023-24)
- religiosity
Average Pew religiousness scale score (0-8; 2023-24)
- religiosity_3cat
Three-category Pew religiousness scale (2023-24)
- religious_text_weekly
Percentage reading religious texts weekly or more (PRRI 2025)
- religious_unaffiliated
Percentage religiously unaffiliated: atheist, agnostic, or nothing in particular (PRRI 2025)
- rent_burdened
Renters spending at least 30% of income on rent (percent; 2024)
- renter_percent
Percentage of occupied housing units that are renter-occupied (2024 ACS, table B25003)
- right_to_work
State has a right-to-work law (2026)
- same_sex_marriage
Percentage favoring legal same-sex marriage (PRRI 2025)
- schools_avg_salary
Average salary of public school teachers (2016). From the National Education Association
- schools_spend
Expenditure per student in average daily attendance (2017). From the National Education Association
- schools_st_ratio
Students enrolled per teacher (2016). From the National Education Association
- smokers
Age-adjusted percentage of adults who currently smoke cigarettes (2024; Tennessee 2023)
- south
Southern state?
- speak_english_only
Percentage age 5 or older speaking only English at home (2024 ACS, table S1601)
- special_ed_funding_supports
Special-education targeted funding-support index (0-3)
- state
State name
- state_board_fully_elected
State board of education fully elected (2026; 1 = yes, 0 = no)
- state_control
Unified state control: Democrat, Split, or Republican; Nebraska is missing (NCSL 2026)
- state_govt_rank
U.S. News & World Report 2025 Best States overall rank
- state_preK_4yo_pct
Percentage of four-year-olds enrolled in state-funded pre-K (2023-24)
- state_preK_quality
NIEER state pre-K quality standards score (2023-24; 0-10)
- state_preK_spending_per_child
State pre-K spending per enrolled child (2023-24 dollars)
- stateid
Two-letter postal abbreviation for state name
- stateleg_black
Percentage of state legislators identified as Black/African American (NCSL, spring 2023)
- stateleg_dem
Democratic share of filled state-legislative seats (percent; 2026)
- stateleg_dem_margin
Democratic seat percentage minus Republican seat percentage (NCSL 2026)
- stateleg_hispanic
Percentage of state legislators identified as Hispanic/Latino (NCSL, spring 2023)
- stateleg_other
Other-party share of filled state-legislative seats (percent; 2026)
- stateleg_prof_rank
Rank of state legislative professionalism based on the 2021 Squire Index
- stateleg_prof_score
Squire Index of state legislative professionalism (2021)
- stateleg_rep
Republican share of filled state-legislative seats (percent; 2026)
- stateleg_women
Percentage of state legislators who are women (NCSL Women in State Legislatures, 2025)
- stateleg_women_count
Number of women state legislators (NCSL Women in State Legislatures, 2025)
- suicide_rate
Age-adjusted suicide death rate per 100,000 population (2024)
- tax_competitiveness
Tax Foundation 2026 State Tax Competitiveness Index score
- tax_source
Largest source of combined state and local tax collections (FY2023)
- teen_birth_rate
Teen birth rate per 1,000 females ages 15-19 (2024)
- term_limits
Does the state currently limit state legislators' terms? (1 = yes, 0 = no; NCSL, 2026)
- trump2020
Trump two-party vote percentage in 2020 election
- trump2024
Donald Trump two-party vote percentage in 2024 election
- turnout24_change20
Percentage-point change in VEP turnout from 2020 to 2024 (UF Election Lab)
- turnout24_rank
Rank among the 50 states by 2024 VEP turnout; 1 is highest (UF Election Lab)
- under18
Percentage of the population under age 18 (2024 ACS, table B01001)
- unemployment
Percentage of the civilian labor force unemployed (2024 ACS, table B23025)
- unified_control
One party controls both legislative chambers and the governorship (1 = yes, 0 = no; NCSL 2026)
- uninsured
Population without health insurance (percent; 2024)
- uninsured_0_64
Population ages 0-64 without health insurance (percent; 2024)
- unionized
Percentage of employed wage and salary workers who were union members (2025)
- universal_school_meals
Statewide universal free school breakfast and lunch (2025-26; 1 = yes, 0 = no)
- unsheltered_homeless_pct
Percentage of people experiencing homelessness who were unsheltered (January 2024)
- urban
Percentage of the state population living in urban areas (2020 Census, table P2)
- vap24
Voting-age population in 2024 (UF Election Lab)
- vap24_turnout
2024 general-election turnout as a percentage of the voting-age population (UF Election Lab)
- vep20_turnout
Voting-eligible population turnout (percent; 2020)
- vep24
Voting-eligible population in 2024 (UF Election Lab)
- vep24_turnout
2024 general-election turnout as a percentage of the voting-eligible population (UF Election Lab)
- veteran_percent
Percentage of the civilian population age 18 or older who are veterans (2024 ACS, table B21001)
- volunteer_hrs_pc
Estimated annual formal-volunteer hours per state resident age 16 or older (2023)
- volunteer_rate
Residents volunteering through an organization (percent; 2023)
- voter_id_law
Identification-document requirement for in-person voting (NCSL, April 24, 2026)
- white_percent
Percentage White alone and not Hispanic or Latino (2024 ACS, table B03002)
- work_from_home
Percentage of workers age 16 or older who usually worked from home (2024 ACS, table B08301)
Source
Data sources vary. See Appendix of printed textbook for further information.
Hypothetical Student Directory for An R Companion to Political Analysis, Fourth Edition
Description
Directory information for university students
Usage
students
Format
A data frame with 100 rows and 7 variables.
- id_number
Unique identification number for each subject
- last_name
Last name of student
- first_name
First name of student
- gender
Gender of student
- campus
Campus attended
- athlete
Whether student has athletic scholarship
- year_born
Year of birth
- year_in_school
Year in school
- modality
Mode of attendance
- major
Academic major
Source
Barry C. Edwards and Philip H. Pollock, III
Calculates the Somers' d measure of association for a cross-tabulation.
Description
Given a table of conditional frequencies, tablesomersDC calculates and returns Somers' D, a measure of association between two ordinal-level variables.
Usage
tablesomersDC(tab, dep = 1, digits = 3)
Arguments
tab |
The conditional frequencies of a cross-tabulation. The dependent and independent variable in cross-tabulation should be be ordinal-level (ordered factors). |
dep |
which dimension stands for the dependent variable (1 = ROWS, 2 = COLS), default is 1. |
digits |
Number of decimal places reported in result (defaults to 3). |
Value
Returns the value of Somers' D.
Examples
library(RCPA4)
conditional.frequencies <- table(dv=states$lgbtq_equality_5cat, iv=states$religiosity_3cat)
tablesomersDC(tab=conditional.frequencies)
One and two-sample difference of means tests (t-tests) with confidence intervals.
Description
Conducts one and two-sample difference of means tests (t-tests). Options for weighting observations, known population standard deviation, equal or unequal variances, paired observations. Numeric-looking factor or character labels, such as "10" and "20", are interpreted as their displayed numeric values.
Usage
testmeansC(x1, x2, w = NULL, data = NULL, dv, iv, digits = 2,
var.equal = FALSE, paired = FALSE, pop.sd = FALSE, var.test = FALSE,
printC = FALSE, conf = 95, plot = TRUE, main = NULL, xlab = NULL,
xlim = NULL, table = TRUE, ...)
Arguments
x1 |
The first variable to be compared (mean of x1 will be compared to mean of x2). Must be numeric variable. Should be in the form dataset$var, unless dataset specified with data argument. |
x2 |
The variable (or number) to which x1 is compared. Should be in the form dataset$var, unless dataset specified with data argument. You can set x2 equal to a number to conduct a one sample means test. For example, to test whether x1 could have population mean of 50, you'd set x2 = 50. |
w |
(Optional) Weights variable (optional). Should be in the form dataset$var, unless dataset specified with data argument. |
data |
(Optional) The dataset that contains x1, x1 and x2, or dv and iv. |
dv |
The dependent variable. Must be numeric variable. Should be in the form dataset$var, unless dataset specified with data argument. |
iv |
The independent variable. Should have two distinct values (like treatment and control). Should be in the form dataset$var, unless dataset specified with data argument. |
digits |
(Optional) Number of digits to report after decimal place, optional (default: 2). |
var.equal |
(Optional) With two-sample tests, do you want to assume equal variances? (default: FALSE) |
paired |
(Optional) With two-sample tests, are the observations paired? (default: FALSE) |
pop.sd |
(Optional) If the population standard deviation is known, you can specify it. |
var.test |
(Optional) If set to TRUE, will test the assumption that two sample variance are equal using an F test. Default is FALSE. The var.test option implemented for both weighted and unweighted analysis. If you are not using sample weights, you can supplement this F test with additional tests such as |
printC |
(Optional) Do you want results printed to .html file in your working directory? Default is FALSE. Set to TRUE to print results. |
conf |
(Optional) Desired confidence level, as percentage (default: 95) |
plot |
(Optional) Do you want a plot of the confidence interval of the difference of means? (default: TRUE) |
main |
(Optional) Main title for plot of confidence interval of difference |
xlab |
(Optional) Label for x-axis of plot of confidence interval of difference |
xlim |
(Optional) A vector (of length 2) specifying the range of the x-axis, useful to zoom in on CI. |
table |
(Optional) Display result tables, including the optional
equal-variance test table? Defaults to |
... |
(Optional) Additional arguments passed to |
Value
Invisibly returns a structured list with stable keys:
descriptive_table, test_stats_table, ci_table, and variance_test_table
(NULL when optional analysis is not computed).
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
Equal-variance table
Use var.test = TRUE to compute the optional equal-variance test. Its table
is displayed only when table = TRUE. With table = FALSE, the test is
still computed and returned in variance_test_table, but its table is
omitted from console and HTML output. Use var.test = FALSE to skip the test.
RCPA4 Package Tutorial Videos
-
Testing Means with RCPA4 Package's testmeansC Function 12:22
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 9.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp.201-215. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Hypothesis Tests with One and Two Samples, Compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site, find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
# one sample test against hypothesized value
testmeansC(x1=world$literacy, x2=80)
# with x1 and x2
testmeansC(x1=ft_trump_post, x2=ft_vance_post, w=wt, data=anes)
# with paired x1 and x2
testmeansC(x1=anes$ft_trump_post, x2=anes$ft_trump_pre, w=anes$wt, paired=TRUE)
# with dv and iv
testmeansC(dv=anes$ft_big_business, iv=anes$gender_s_sex, w=anes$wt)
Tests the difference between two sample proportions, or difference between sample proportion and hypothesized value, with options for weighted observations, confidence intervals
Description
Difference of proportions test with optional sample weights. Reports P-value of two-tailed significance test. Currently limited to testing one response from one dataset. If you want to compare x1 from dataset1 and x2 from dataset2, you can create new dataframe to test as dv ~ iv where dv is vector of x1 and x2 values and iv is vector identifying the source (i.e. dataset1 and dataset2). If you want to compare different responses, such as "Yes" value for x1 and "Agree" value for x2, you will need to transform one of the variables so they have comparable response values.
Usage
testpropsC(x1, x2, w = NULL, data = NULL, dv, iv, digits = 3,
response = NULL, printC = FALSE, conf = 95, plot = TRUE,
main = NULL, xlab = NULL, xlim = NULL, table = TRUE, ...)
Arguments
x1 |
A categorical variable |
x2 |
Value or variable to compare x1 against. |
w |
(Optional) Weights variable. |
data |
(Optional) Specify name of dataset (data frame) with x1 and x2 variables (or dv and iv). |
dv |
Dependent variable |
iv |
Independent variable, should have only two unique values. For comparison purposes, group1 will be first level of iv and group2 will be the second level of iv. To change order of groups, you can modify levels(iv). |
digits |
(Optional) Number of digits to report after decimal place, optional (default: 3). |
response |
(Optional) Identify the response value you wish to compare. If not specified, the function will compare first value of the dv (or x1 variable). If you want to group multiple responses together, use transformC to make dummy variable. |
printC |
(Optional) Do you want results printed to .html file in your working directory? Default is FALSE. Set to TRUE to print results. |
conf |
(Optional) Desired confidence level, as percentage (default: 95) |
plot |
(Optional) Do you want a plot of the confidence interval of the difference of proportions? (default: TRUE) |
main |
(Optional) Main title for plot of confidence interval of difference |
xlab |
(Optional) Label for x-axis of plot of confidence interval of difference |
xlim |
(Optional) A vector (of length 2) specifying the range of the x-axis, useful to zoom in on CI. By default, |
table |
(Optional) Do you want summary tables reported? (default: TRUE) |
... |
(Optional) Additional arguments passed to plot function for the CI plot |
Value
Invisibly returns a structured list with stable keys:
descriptive_table, z_test_table, and ci_table
(NULL where optional analysis is not computed).
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Result tables
The table argument controls display of the main result tables separately
from headings and informational messages. Set table = FALSE to omit those
tables from console output and HTML output. See the Value section for the
results returned by this function and how to save them for further use.
The printC argument controls HTML output; printC = FALSE does not suppress
console tables. Turning off tables does not turn off plots.
RCPA4 Package Tutorial Videos
-
Testing Proportions with RCPA4 Package's testpropsC Function 27:33
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 9.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp.201-215. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Hypothesis Tests with One and Two Samples, Compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
# one sample test: x1 variable against hypothesized value (of x2)
testpropsC(x1=anes$favor_opps_bckgrnd, x2=.500, w=anes$wt, response="Favor a great deal",
xlim=c(0, .2))
# two sample test x1 versus x2
testpropsC(x1=has_sons, x2=has_daughters, w=wt, data=anes,
response="Yes", xlim=c(-.10, .10))
# test of proportions dv by iv
testpropsC(dv=mrtl_stts_5_ctgry, iv=gender_s_sex, w=wt, data=anes, response="Widowed",
xlim=c(-.10, 0))
Returns new variables by transforming existing dataset variables (e.g. dummy variables, standardized variables, rank orders)
Description
Given a variable x, the transformC function generates and returns a tranformed version of x. For example, transformC can take a variable x and return standardized x, or the log of x.
Usage
transformC(type, x, data = NULL, response = NULL, cutpoints = NULL,
groups = NULL, confirm = TRUE, ...)
Arguments
type |
The type of transformation to be made to x. Options include:
|
x |
The variable to be transformed, a variable that already exists, should be in dataset$var form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains x variable. |
response |
(Optional) For |
cutpoints |
(Optional) For |
groups |
(Optional) For |
confirm |
(Optional) By default, |
... |
(Optional) Additional arguments pass to |
Value
A transformed version of x variable, a vector with the same length as x, unless type="dummy.set" in which case transformC returns a data.frame.
Console output
Additional RCPA4 headings are controlled by the session option
RCPA4.verbose, which defaults to TRUE. Use
options(RCPA4.verbose = FALSE) to suppress these headings, or change the
setting through helpC(6). The setting applies for the current R session.
Thee RCPA4.verbose option does not suppress result tables, plots, messages,
warnings, errors, or interactive prompts. The option RCPA4.slow = FALSE
disables the package's optional pauses independently of verbosity.
Confirmation output
Use confirm = FALSE to return the transformed variable without the
confirmation prompt or transformation-results heading. Informational
messages about the transformation are controlled separately by
suppressMessages().
RCPA4 Package Tutorial Videos
-
Transforming Variables with RCPA4 Package's transformC Function 22:40
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook References
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 3.
Philip H. Pollock and Barry C. Edwards, The Essentials of Political Analysis, 6th Edition (Sage Publications, 2020), pp. 55-64. ISBN-13: 978-1506379616; ISBN-10: 150637961.
Online Resources
-
R Tutorials & Resources for Creating and Transforming Variables, Compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
-
Political Science Data Web Site: Find datasets for your own research and resources to help with the analysis.
Examples
library(RCPA4)
# don't use confirm=FALSE until you've tested the function call
transformC("percent.rank", anes$ft_dem_party, confirm=FALSE)
transformC("rank", anes$ft_dem_party, confirm=FALSE)
transformC("whole", runif(min=0,max=100,n=20), confirm=FALSE)
Welcomes users to RCPA4 and confirms that the package is available
Description
Welcomes users to RCPA4 package for An R Companion to Political Analysis, 4th Edition and provides basic information about using Companion functions and datasets.
Usage
welcomeC()
Value
No value returned
RCPA4 Package Tutorial Videos
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook Reference
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 1.
Online Resources
-
R Tutorials & Resources for Getting Started with R, Compiled by Barry C. Edwards
-
Sage Edge Resources for Political Analysis Series, for streaming videos, flashcards, and more student resources for textbooks by Pollock and Edwards, from Sage Publications.
Examples
library(RCPA4)
# Welcome message from RCPA4 package.
welcomeC()
An interactive game to practice using R functions.
Description
A fun, interactive game to practice using R functions. Players must execute functions to make widgets per strict specifications to win the game. The Widget Factory needs your help!
Usage
widgetFactory()
Value
No value returned
RCPA4 Package Tutorial Videos
-
Complete Playlist of RCPA4 Package Tutorial Videos, includes video for this function and many more.
Textbook Reference
Barry C. Edwards and Philip H. Pollock, An R Companion to Political Analysis, 4th Edition (Political Science Data, Forthcoming 2026), Chapter 1.
Online Resource
-
Tutorials & Resources for Using R for Data Analysis, compiled by Barry C. Edwards
Examples
library(RCPA4)
# Play the Widget Factory game
if (interactive()) {
widgetFactory()
}
World dataset for R Companion to Political Analysis, Fourth Edition
Description
A dataset with variables about countries in the world. This dataset is used to demonstrate application of R to political analysis. See book Appendix for variable names and descriptions.
Format
A data frame with 169 rows and 234 variables.
- arda_code
Country numerical code. From Association of Religion Data Archives
- bribe_judge
Proportion of survey respondents from country reporting that they or member of family paid bribe to legal/judicial system in last year. From Global Corruption Barometer
- bribe_police
Proportion of survey respondents from country reporting that they or member of family paid bribe to police in last year. From Global Corruption Barometer
- broadband
Broadband subscription per 100 people in 2017. From Our World in Data
- business_starts
Number of new corporations registered annually. From World Bank's World Development Indicators
- cabrv
Three-letter abbreviation of country name assigned by International Standards Organization
- ccode
Numeric country code based on the ISO standard
- ciaedex
Percent of GDP spent on education (CIA)
- ciagdpag
Composition of GDP: Agricultural sector (CIA)
- ciagdpin
Composition of GDP: Industrial sector (CIA)
- ciagdpsv
Composition of GDP: Service sector (CIA)
- civil_war
Civil war intensity, 2008
- co2_percap
Carbon dioxide emissions excluding land-use change and forestry, in metric tonnes of CO2-equivalent per person, 2024.
- co2e_percap
Total greenhouse gas emissions excluding land-use change and forestry, in metric tonnes of CO2-equivalent per person, 2024.
- energy_renew_percent
Renewable energy consumption as a percentage of total final energy consumption.
- ocean_health
Ocean Health Index score for waters associated with a coastal country, ranging from 0 to 100.
- coastal
Whether the country has an ocean or sea coastline.
- rainfall_mm
Long-term average annual precipitation over the country's land area, in millimeters per year.
- forest_percent
Forest area as a percentage of total land area.
- freshwater_percap
Renewable internal freshwater resources per person, in cubic meters per year.
- unclos_ratified
Whether the country is a party to the United Nations Convention on the Law of the Sea.
- migratory_species_treaty
Whether the country is a party to the Convention on Migratory Species.
- nagoya_protocol
Whether the country is a party to the Nagoya Protocol on access and benefit sharing.
- bbnj_agreement
Whether the country is a party to the BBNJ Agreement on marine biodiversity beyond national jurisdiction.
- colony
Colony of what country? (CIA)
- compulsory_voting
Compulsory voting in national elections in 2025, including whether sanctions are enforced. From V-Dem
- confidence
Confidence in institutions scale (World Values Survey)
- conflict_index
Global Peace Index score for 2026, with higher values indicating less peaceful conditions.
- conflict_internal
Number of internal conflicts between govt and groups in country without intervention from other countries. From UCDP/PRIO Database
- conflict_internat
Number of internal conflicts between govt and groups in country with intervention from other countries (on one or both sides). From UCDP/PRIO Database
- corp_tax_rate
Corporate tax rate. From Heritage Foundation's 2021 Index of Economic Freedom
- corrupt_perception
Corruption perception index. From Transparency International
- country
Country or territory name used in the RCPA4 World Dataset
- coup_attempts
Number of attempted coups d'etats since 1950. From Jonathan Powell
- coups
Number of successful coups d'etats since 1950. From Jonathan Powell
- death_penalty_status
Legal status of death penalty (1 = Abolished, 2 = Abolished Except for Extraordinary Crimes, 3 = Abolished in Practice, 4 = Uses Death Penalty). From Death Penalty Information Center
- debt_percent_gdp
Public debt as a percentage of GDP. From Heritage Foundation's 2021 Index of Economic Freedom
- dem_other
Percentage of other democracies in region
- dem_other5
Percentage of other democracies in region: 5 categories
- district_size3
Average number of members per district. From World Values Survey
- dnpp_3
Effective number of parliamentary parties
- dpi_cemo
Is chief executive a military officer? 0 = no, 1 = yes. From World Bank's Database of Political Institutions
- dpi_system
National political system (0 = Presidential, 1 = Assembly-elected President, 2 = Parliamentary). From World Bank's Database of Political Institutions
- durable
Number of years since the last regime transition as of 2018 (Polity)
- econ_compete
Measure of global economic competitiveness. From World Economic Forum
- econ_freedom
Heritage Foundation rating of overall economic freedom. From 2021 Index of Economic Freedom
- econ_freedom_5cat
Heritage Foundation assessment of overall economic freedom. From 2021 Index of Economic Freedom
- educ_f_avgyrs
Average schooling years, female (25+). From Educational Attainment Dataset by Barro and Lee
- educ_f_none
Percentage of females with no schooling (25+). From Educational Attainment Dataset by Barro and Lee
- educ_m_avgyrs
Average schooling years, male (25+). From Educational Attainment Dataset by Barro and Lee
- educ_m_none
Percentage of males with no schooling (25+). From Educational Attainment Dataset by Barro and Lee
- educ_quality
Average rating of quality of educational system, ranges 1-7 (higher values = better quality). From World Economic Forum
- effectiveness
Government effectiveness scale (Kaufmann, 2002)
- eiu_democ_4cat
Level of democracy in 2020, 4 ordinal categories. From Economist Intelligence Unit
- eiu_democ_bin
Is the country classified by the Economist Intelligence Unit as a full or flawed democracy in 2025?
- eiu_democ_score
Economist Intelligence Unit Democracy Index score for 2025, ranging from 0 to 10; higher values indicate stronger democracy.
- election_integrity
Average of expert evaluation of integrity of country's electoral system. From Electoral Integrity Project
- election_violence_post
Were there riots and protest after election? From National Elections Across Democracy and Autocracy
- election_violence_pre
Were there riots and protest before election? From National Elections Across Democracy and Autocracy
- enpp3_democ
Effective number of parliamentary parties: 3 categories
- enpp3_democ08
Effective number of parliamentary parties. From World Values Survey
- enpp_3
Effective number of parliamentary parties
- eu
EU member state as of June 2021 (yes/no)
- fdi_inflow
Inflow of foreign direct investment (in millions of U.S. dollars). From Heritage Foundation's 2021 Index of Economic Freedom
- fertility
Total fertility rate: average number of births per woman; latest available World Bank value
- fh_democ_3cat
Freedom House rating of democracy, 3 ordinal categories. From 2021 report
- fh_democ_score
Freedom House aggregate political-rights and civil-liberties score for 2025, ranging from 0 to 100; higher values indicate greater freedom.
- fh_internet_3cat
Level of Internet freedom in country, 3 ordinal categories (1 = Not Free, 2 = Partly Free, 3 = Free). From Freedom House, 2021 Report on Internet Freedom
- fh_internet_score
Measure of Internet freedom in country in 2021; combines measures of obstacles to access, limits on content, and violations of user rights. Ranges 0 to 100 (with 100 = most freedom). From Freedom House
- frac_eth
Ethnic factionalization (Alesina et al., 2003)
- frac_eth2
Ethnic factionalization, divided into High and Low categories
- frac_eth3
Level of ethnic fractionalization: 3 categories (Low, Medium, High)
- frac_lang
Language factionalization (Alesina et al., 2003)
- frac_relig
Religious factionalization (Alesina et al., 2003)
- gas_production
In millions of barrels of oil equivalent. From Michael Ross's Oil and Gas Data, 1932-2014
- gdp_growth
Annual economic growth rate, 5-year average. From Heritage Foundation's 2021 Index of Economic Freedom
- gdp_percap
GDP per capita at purchasing power parity in constant 2021 international dollars; latest available World Bank value in July 2026 download
- gdp_percap_5cat
GDP per capita at purchasing power parity, July 2026 World Bank download, grouped into five ordered RCPA categories
- gender_equal3
Gender empowerment measure, 3 categories. From World Values Survey
- gender_inequality
UNDP Gender Inequality Index (0 = least inequality, 1 = greatest inequality), 2023
- gini_index
GINI index (of income inequality). Most recent estimates from CIA World Factbook (as of June 2021)
- global_social
Social globalization measured by personal contacts of citizens, information flows, and cultural proximity. From KOF Index of Globalization
- govt_help_cap
Capacity of state to provide for needy citizens. From Fund for Peace, Fragile States Index
- govt_integrity
Rating of government integrity. From Heritage Foundation's 2021 Index of Economic Freedom
- govt_per_gdp
Government spending (all types) as a percentage of GDP
- govt_quality
Measure of the quality of government. From International Country Risk Guide of Political Risk Group
- gri
Government Restrictions Index based on 20 indicators of ways that governments restrict religion, including through coercion and force. From Pew Research Center on Global Restrictions of Religion Report, 2016 data
- grp_name
Name of the religion preferred by the government in 2015 (based on multidimensional measure of government favoritism)
- grp_score
Measure of Government Religious Preference in 2015, how strongly government favors one religion over others
- happiness
Measure of how happy citizens are. From World Happiness Report
- hdi
Human development index (HDI) value (as of June 10, 2021). Human development dimensions include having long and healthy lives, being knowledgeable, and enjoying a decent standard of living. From UNDP Human Development Report
- hiv_percent
Percentage of adults ages 15-49 living with HIV.
- homicide_rate
Number of intentional homicides per 100,000 persons. From UNODC Global Study on Homicide 2013 (where 2012 data missing from report, last reported year used, typically 2011)
- hospital_beds
Hospital beds per 1,000 people.
- human_flight
Measure of human flight and brain drain from country. From Fund for Peace, Fragile States Index
- icc_treaty_ratified
Whether the country is currently a state party to the Rome Statute of the International Criminal Court (Yes/No)
- immigrants_percent
International migrant stock as a percentage of population; latest available World Bank value
- imprisonment_rate
Number incarcerated per 100,000 persons. From World Prison Brief
- income_tax_rate
Income tax rate. From Heritage Foundation's 2021 Index of Economic Freedom
- indep_judiciary
Does country have an independent judiciary? (1 = yes). From Political Constraints Index Dataset
- indy
Year of independence (CIA)
- infant_mortality
Infant deaths before age one per 1,000 live births.
- inflation
Annual inflation rate. From Heritage Foundation's 2021 Index of Economic Freedom
- internet_users
Percentage of population that uses the Internet (as of 2020 or 2021)
- judicial_effectiveness
Rating of effectiveness of country's judiciary. From Heritage Foundation's 2021 Index of Economic Freedom
- judicial_indep_wef
Average rating of judicial independence, ranges 1-7. From World Economic Forum
- laws_protect_prop
Property rights index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- legal_origin
Legal origin of commercial code of country (1 = English Common Law, 2 = French Commercial Code, 3 = Socialist/Communist Laws, 4 = German Commercial Code, 5 = Scandinavian Commercial Code). From LaPorta, Lopez de-Silanes, Shleifer, and Vishny (1998)
- legal_quality
Measure of quality of country's legal institutions. From the Institutional Quality Dataset
- life_expectancy
Life expectancy at birth, total years; latest available World Bank value
- lifeex_f
Life expectancy at birth among females, total years; latest available World Bank value
- lifeex_m
Life expectancy at birth among males, total years; latest available World Bank value
- literacy
Literacy rate (CIA)
- media_access_cand
Does country provide free or subsidized media access for political candidates? (1 = yes) From Institute for Democracy and Electoral Assistance
- media_access_parties
Does country provide free or subsidized media access for political parties? (1 = yes). From Institute for Democracy and Electoral Assistance
- median_age
Median age in 2025 from UN World Population Prospects medium projection via Our World in Data
- migration_net
Net migration, immigrants minus emigrants; latest available World Bank value
- muslim
Are Muslims the predominant religious group?
- oecd
OECD member state as of June, 2021? (yes/no)
- oil
Oil production, in barrels per day (CIA) CIAOIL_P
- oil_production
In metric tons. From Michael Ross's Oil and Gas Data, 1932-2014
- organized_crime
Average rating of the impact of organized crime on the economy, ranges 1-7 (lower values = more impact). From World Economic Forum
- peace_5cat
State of peace in country, 5 ordinal categories. From Visions of Humanity's Global Peace Index 2021 Report
- peace_index
Reversed Global Peace Index score for 2026, with higher values indicating greater peacefulness.
- pmat12_3
Post-materialism, 3 categories (World Values Survey)
- pol_terror_scale_ai
Political terror scale. Ordinal scale from 1-5 of how much government terrorizes country's citizens, with 1 corresponding to very little oppression by government. From Amnesty International
- pol_terror_scale_hrw
Political terror scale. Ordinal scale from 1 to 5 of how much government terrorizes country's citizens, with 1 corresponding to very little oppression by government. From Human Rights Watch
- polity_score
Polity5 combined democracy-autocracy score for 2018, ranging from -10 for strongly autocratic regimes to +10 for strongly democratic regimes. This is a historical measure; Polity5 has not been updated beyond 2018. Source: Center for Systemic Peace.
- pop_0_14
Percentage of population ages 0-14; latest available World Bank value
- pop_15_64
Percentage of population ages 15-64; latest available World Bank value
- pop_65_older
Percentage of population ages 65 and older; latest available World Bank value
- pop_growth
Annual population growth percentage; latest available World Bank value
- pop_urban
Percentage of population living in urban areas; latest available World Bank value
- population
Total population; latest available World Bank value
- population_3cat
Total population grouped into three ordered RCPA categories using the latest available World Bank value
- population_density
Population density, people per square kilometer of land area; latest available World Bank value
- poverty
Percentage of the population below the poverty line
- pr_sys
Proportional representation electoral system? From the Institute for Democracy and Electoral Assistance
- press_freedom_fh
Measure of freedom of the country's press. Based on Freedom House Freedom of the Press Report 2015, fit to 0-10 range
- press_freedom_rsf
Measure of freedom of the country's press. From Reporters Sans Frontiers
- protact3
Protest activity (World Values Survey)
- refugees_from
Refugees under UNHCR mandate by country or territory of origin; latest available World Bank value
- refugees_impact
Measure of impact of population displacement on country. From Fund for Peace, Fragile States Index
- refugees_in
Refugees under UNHCR mandate by country or territory of asylum; latest available World Bank value
- regime_type3
Regime type. From Cheibub's Democracy Dictatorship dataset
- region
Region name
- regionun
United Nations region
- religion
Largest religion by proportion (UN)
- reserved_seats
Does country reserve seats in national legislature for any group (e.g., women or young people)? From Inter-parliamentary Union
- rights_assn
Freedom of assembly and association, ordinal scale 0-2. From CIRI Human Rights Data Project
- rights_dommov
Freedom of domestic movement, ordinal scale 0-2. From CIRI Human Rights Data Project
- rights_formov
Freedom of foreign travel and emigration in 2025, recoded into three ordered categories. From V-Dem
- rights_injud
High-court independence in 2025, recoded into three ordered categories. From V-Dem
- rights_law_index
Measure of violations of human right and rule of law. From Fund for Peace, Fragile States Index
- rights_relfree
Freedom of religion in 2025, recoded into three ordered categories. From V-Dem
- rights_speech
Freedom of speech, ordinal scale 0-2. From CIRI Human Rights Data Project
- rights_treaties
Number of international human rights treaties ratified (out of 16 possible). From UNHRC
- rights_wecon
Women's economic rights, ordinal scale 0-2. From CIRI Human Rights Data Project
- rights_wopol
Women's political rights, ordinal scale 0-2. From CIRI Human Rights Data Project
- rights_worker
Women's social rights, ordinal scale 0-2. From CIRI Human Rights Data Project
- schools_internet
Average rating of internet availability in schools, ranges 1-7 (higher values = more extensive). From World Economic Forum
- self_employed
Percentage of labor force that is self-employed. From World Bank's World Development Indicators
- sexratio
Sex ratio at birth, male births per 100 female births; latest available World Bank value
- shi
Social Hostilities Index based on 13 indicators of ways in which private individuals and social groups infringe upon religious beliefs and practices. From Pew Research Center on Global Restrictions of Religion Report, 2016 data
- soldiers_percent
Percentage of labor force in the military. From World Bank's World Development Indicators
- soldiers_total
Total number of people in the military. From World Bank's World Development Indicators
- spendeduc
Public expenditure on education as a percentage of GDP (UN)
- spendhealth
Domestic general government health expenditure as a percentage of GDP.
- spendmil_wdi
Military expenditure as a percentage of GDP; latest available World Bank/SIPRI value
- tariff_rate
Tariff rate on imports. From Heritage Foundation's 2021 Index of Economic Freedom
- taxes_percent_gdp
Taxes (all forms) as a percentage of gross domestic product. From Heritage Foundation's 2021 Index of Economic Freedom
- terror_index_voh
Measure of the impact of terrorism on the country. From Visions of Humanity
- trade_percent_gdp
Exports plus imports of goods and services as a percentage of GDP; latest available World Bank value
- typerel
Predominant religion
- unemployment
Percentage of labor force that is unemployed (available/seeking employment but not employed). From CIA World Factbook (most recent estimates available as of June 2021)
- unexp_rd
Public expenditure on research and development as a percentage of GDP (UN)
- unfempf
Ratio of female-to-male formal employment rates
- unin_inc
Inequality-adjusted income index (2010, UN)
- unineduc
Inequality-adjusted education index (2010)
- unions
Union density
- unjourn
Number of verified cases of journalists imprisoned in 2009 (UN)
- unlit
Adult literacy rate (percentage of population age 15 or older) (UN)
- unmobcov
Percentage of the population covered by a mobile phone network (2008, UN)
- unmort_f
Adult mortality rate among females, per 1,000 female adults; latest available World Bank value
- unmort_m
Adult mortality rate among males, per 1,000 male adults; latest available World Bank value
- unnewsp
Daily newspapers per thousand people (2004, UN)
- unnoncom
Age-standardized deaths from noncommunicable diseases per 100,000 people.
- unpop30
Projected 2030 population in millions, UN medium scenario via Our World in Data
- unremitp
Per capita remittance inflows in U.S. dollars (2008)
- unremitt
Remittance inflows as a percentage of GDP (2008)
- unsati
Overall life satisfaction, most recent measure during 2006-2009 (0-10, higher means more satisfied) (UN)
- unsatif
Overall life satisfaction among females, most recent measure during 2006-2009 (UN)
- unsatjob
Percentage of employed who are satisfied with their job (UN)
- unsatliv
Percentage who are satisfied with their standard of living (UN)
- unseced
Percentage of the population ages 25 and older with at least secondary education (UN)
- vdem_2cat
Democracy or autocracy in 2025, derived from V-Dem's Regimes of the World classification
- vdem_4cat
Regime type in 2025, ordered from liberal democracy to closed autocracy. From V-Dem
- vdem_edi_score
Electoral Democracy Index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_ldi_score
Liberal Democracy Index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vi_rel3
Percent saying religion very important, 3 categories
- violence_cost
Economic cost of violence on national economy. Measured as a percentage of GDP. From Visions of Humanity
- votevap10s
Turnout of voting age population: average of both presidential and parliamentary elections in 2010s. From the Institute for Democracy and Electoral Assistance
- womenleg
Women as a percentage of the lower or unicameral legislative chamber in 2025. From V-Dem
- womyear
Year women first enfranchised. From Inter-parliamentary Union
- womyear2
Women's suffrage. From Inter-parliamentary Union
- youngleg
Percentage of lower house of legislature aged 40 years or younger, as of June 2021. From the Inter-parliamentary Union
- vdem_participatory_score
Participatory Democracy Index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_deliberative_score
Deliberative Democracy Index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_egalitarian_score
Egalitarian Democracy Index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_judicial_constraints
Judicial constraints on the executive in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_rule_of_law
Rule of Law Index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_access_justice
Secure and effective access to justice in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_political_corruption
Political Corruption Index in 2025, ranging from 0 (less corruption) to 1 (more corruption). From V-Dem
- vdem_freedom_expression
Freedom of expression and alternative information in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_civil_society
Civil Society Participation Index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_women_empowerment
Women's Political Empowerment Index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_civil_liberties
Civil Liberties Index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_physical_integrity
Physical Integrity Index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_highcourt_independence
V-Dem model estimate of high-court independence in 2025; higher values indicate greater independence
- vdem_property_rights
Property Rights Index in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_freedom_religion
V-Dem model estimate of freedom of religion in 2025; higher values indicate greater freedom
- vdem_freedom_domestic_movement
Freedom of domestic movement and residence in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_freedom_foreign_movement
V-Dem model estimate of freedom of foreign travel and emigration in 2025; higher values indicate greater freedom
- vdem_freedom_association
Freedom of association for political parties and civil-society organizations in 2025, ranging from 0 (low) to 1 (high). From V-Dem
- vdem_education_equality
V-Dem model estimate of equality in access to high-quality basic education in 2025; higher values indicate greater equality
- vdem_health_equality
V-Dem model estimate of equality in access to high-quality basic health care in 2025; higher values indicate greater equality
- vdem_gender_quota
National gender quota for the lower or unicameral legislative chamber in 2025. From V-Dem
- vdem_social_consensus
V-Dem model estimate of social consensus on major political issues in 2025; higher values indicate less polarization
- maternal_mortality
Maternal deaths per 100,000 live births.
- tb_incidence
Estimated new and recurrent tuberculosis cases per 100,000 people.
- adult_obesity
Percentage of adults age 18 and older with a body mass index of 30 or higher, age-standardized.
- dpt_immunization
Percentage of children ages 12-23 months receiving three doses of DPT vaccine.
- out_of_pocket_health
Household out-of-pocket spending as a percentage of current health expenditure.
- uhc_service_index
Universal Health Coverage service coverage index, ranging from 0 to 100; higher values indicate broader essential-service coverage.
Source
Data sources vary. See Appendix of printed textbook for further information.
Calculates Correlation Coefficient Between Two Numeric Variables Uses RCPA4's internal weighted correlation helper.
Description
Given two numeric variables, wtd.cor reports correlation coefficient, works with sampling weights.
Usage
wtd_cor(x1, x2, w = NULL, data = NULL, digits = NULL, stats = FALSE,
...)
Arguments
x1 |
A variable (must be numeric), should be in dataset$var form unless dataset specified in optional data argument. |
x2 |
Another variable, different than x1 (must be numeric), should be in dataset$var form unless dataset specified in optional data argument. |
w |
(Optional) Sampling weights of variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains x (and w) variable. |
digits |
(Optional) Number of decimal places reported in result. Default is NULL (no rounding). |
stats |
(Optional) Do you want inferential statistics for correlation coefficient? (default: FALSE) |
... |
(Optional) Additional arguments passed to the internal weighted correlation helper. |
Value
Returns the coefficient of correlation between x1 and x2 variables, a numeric value.
Examples
library(RCPA4)
wtd_cor(x1=anes$ft_rep_party, x2=anes$ft_trump_pre, w=anes$wt)
wtd_cor(x1=ft_dem_party, x2=ft_harris_pre, w=wt, data=anes)
Creates a Histogram Showing Distribution of Variable Values With Option for Weights Uses RCPA4's internal wtd histogram helper.
Description
Takes in variable and generates histogram plot to show the distribution of its values, works with sampling weights. Bin counts are computed with optional weights.
Usage
wtd_hist(x, w = NULL, data = NULL, breaks = NULL, suggest = TRUE,
main = NULL, xlab = NULL, ...)
Arguments
x |
A variable (must be numeric), should be in dataset$var form unless dataset specified in optional data argument. |
w |
Sampling weights of variable (optional), must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains x (and w) variable. |
breaks |
(Optional) Specifies the breakpoints between bins of the histogram. |
suggest |
(Optional) If TRUE, suggest bar chart when x has very few distinct values. |
main |
(Optional) Main title for histogram; defaults to "Histogram of x". |
xlab |
(Optional) X-axis label for histogram; defaults to "x Values". |
... |
(Optional) Additional arguments passed to the internal wtd histogram helper. |
Value
Generate a histogram plot.
Examples
library(RCPA4)
wtd_hist(x=anes$r_age_election_day, w=anes$wt)
Generates Kurtosis Statistic with Option to Weight Observations
Description
Generates Kurtosis Statistic with Option to Weight Observations
Usage
wtd_kurtosis(x, w = NULL, data = NULL, digits = NULL)
Arguments
x |
Variable (a numeric vector) |
w |
(Optional) Weights variable |
data |
(Optional) Dataset, can be used to abbreviate x to variable name |
digits |
(Optional) Number of digits after decimal point. Default is NULL (no rounding). |
Value
Returns the kurtosis of the variable, a numeric value.
Examples
library(RCPA4)
wtd_kurtosis(x=anes$r_age_election_day, w=anes$wt)
wtd_kurtosis(x=anes$r_age_election_day)
Calculates Mean of Variable With Option for Weights
Description
Takes in variable and calculates its mean, works with sampling weights.
Makes use of the wtd.mean function, part of the Hmisc package. See wtd.stats documentation for details.
Usage
wtd_mean(x, w = NULL, data, digits = NULL, ...)
Arguments
x |
A variable (must be numeric), should be in dataset$var form unless dataset specified in optional data argument. |
w |
(Optional) Sampling weights of variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains x (and w) variable. |
digits |
(Optional) Number of decimal places reported in result. Default is NULL (no rounding). |
... |
(Optional) Additional arguments passed to Hmisc::wtd.mean function. |
Value
Returns the mean of the variable, a numeric value.
Examples
library(RCPA4)
wtd_mean(anes$ft_liberals, w=anes$wt)
wtd_mean(anes$ft_liberals)
wtd_mean(anes$r_age_election_day, w=anes$wt)
wtd_mean(anes$r_age_election_day)
Find Median of Variable with Option to Weight Observations
Description
Takes in a numeric variable or ordered factor and finds its median, with optional sampling weights. Numeric-looking factor labels are interpreted as their displayed numeric values. Ordered factors return the first category whose cumulative weight reaches one-half of the total.
Usage
wtd_median(x, w = NULL, data = NULL, ...)
Arguments
x |
A variable |
w |
(Optional) Sampling weights of variable |
data |
(Optional) Name of dataset that contains x (and w) variable |
... |
(Optional) Additional arguments passed to 'Hmisc::wtd.quantile'. |
Value
Returns the median value of 'x'. For numeric input, returns a numeric value; for factor input, returns the corresponding level label.
Examples
library(RCPA4)
wtd_median(x=anes$ft_biden_pre, w=anes$wt)
wtd_median(x=anes$ft_biden_pre)
Find Mode of Variable with Option to Weight Observations
Description
Takes in variable and finds mode, works with sampling weights.
Usage
wtd_mode(x, w = NULL, data = NULL, ...)
Arguments
x |
A variable |
w |
(Optional) Sampling weights of variable |
data |
(Optional) A dataset |
... |
(Optional) Reserved for backward compatibility. |
Value
Returns the modal value(s) of the variable, if mode exists
Examples
library(RCPA4)
wtd_mode(x=anes$feel_angry, w=anes$wt)
wtd_mode(x=anes$feel_angry)
wtd_mode(x=anes$discrim_us_men, w=anes$wt)
wtd_mode(x=anes$discrim_us_men)
Finds the Quantile Values of Variable With Option for Weights
Description
Takes in variable and calculates desired quantile values, works with sampling weights. Makes use of the wtd.quantile function from the Hmisc package. See wtd.stats documentation for details.
Usage
wtd_quantile(x, w = NULL, data, q = c(5, 10, 25, 50, 75, 90, 95),
digits = NULL, ...)
Arguments
x |
A variable (must be numeric), should be in dataset$var form unless dataset specified in optional data argument. |
w |
(Optional) Sampling weights of variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains x (and w) variable. |
q |
(Optional) The quantiles you want calculated as a number or vector of numbers. Input as percentages. For median only, q=50. For quartiles, q=c(25, 50, 75). |
digits |
(Optional) Number of decimal places reported in result. Default is NULL (no rounding). |
... |
(Optional) Additional arguments passed to Hmisc::wtd.quantile function. |
Value
Returns quantile values of a variable, a vector of numeric values.
Examples
library(RCPA4)
wtd_quantile(x=anes$ft_police, q=c(25, 50, 75), w=anes$wt)
wtd_quantile(x=anes$ft_police, q=c(25, 50, 75))
Calculates Standard Deviation of Variable With Option for Weights
Description
Takes in variable and calculates standard deviation, works with sampling weights. Makes use of the wtd.var function, part of the Hmisc package.
Usage
wtd_sd(x, w = NULL, data, digits = NULL, ...)
Arguments
x |
A variable (must be numeric), should be in dataset$var form unless dataset specified in optional data argument. |
w |
(Optional) Sampling weights of variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains x (and w) variable. |
digits |
(Optional) Number of decimal places reported in result. Default is NULL (no rounding). |
... |
(Optional) Additional arguments passed to Hmisc::wtd.var function. |
Value
Returns the standard deviation of the variable, a numeric value.
Examples
library(RCPA4)
wtd_sd(x=anes$ft_liberals, w=anes$wt)
wtd_sd(x=anes$ft_liberals)
Calculates Skewness of Numeric Variable with Option to Weight Observations
Description
Calculates Skewness of Numeric Variable with Option to Weight Observations
Usage
wtd_skewness(x, w = NULL, data = NULL, digits = NULL)
Arguments
x |
Variable (must be a numeric vector) |
w |
(Optional) Weights variable |
data |
(Optional) Dataset |
digits |
(Optional) Number of digits after decimal point. Default is NULL (no rounding). |
Value
Returns the skewness of the variable, a numeric value.
Examples
library(RCPA4)
wtd_skewness(x=anes$ft_liberals, w=anes$wt)
wtd_skewness(x=anes$ft_liberals)
Calculates Variance of Variable With Option for Weights
Description
Takes in variable and calculates its variance, works with sampling weights. Makes use of the wtd.var function from the Hmisc package. See wtd.stats documentation for details.
Usage
wtd_var(x, w = NULL, data = NULL, digits = NULL, ...)
Arguments
x |
A variable (must be numeric), should be in dataset$var form unless dataset specified in optional data argument. |
w |
(Optional) Sampling weights of variable, must be numeric; should be in dataset$weightvar form unless dataset specified in optional data argument. |
data |
(Optional) Name of dataset that contains x (and w) variable. |
digits |
(Optional) Number of decimal places reported in result. Default is NULL (no rounding). |
... |
(Optional) Additional arguments passed to Hmisc::wtd.var function. |
Value
Returns the variance of the variable, a numeric value.
Examples
library(RCPA4)
wtd_var(x=anes$ft_liberals, w=anes$wt)
wtd_var(x=anes$ft_liberals)