| 1 |
--- |
| 2 |
title: Handling questionnaire items |
| 3 |
output: rmarkdown::html_vignette |
| 4 |
vignette: > |
| 5 |
% \VignetteIndexEntry{Handling questionnaire items} |
| 6 |
% \VignetteEngine{knitr::rmarkdown} |
| 7 |
% \VignetteEncoding{UTF-8} |
| 8 |
--- |
| 9 |
|
| 10 |
```{r,echo=FALSE,message=FALSE} |
| 11 |
knitr::opts_chunk$set(comment=NA, |
| 12 |
fig.align="center", |
| 13 |
results="markup") |
| 14 |
``` |
| 15 |
|
| 16 |
# Motivation |
| 17 |
|
| 18 |
R is a great tool to do data analysis and for data management tasks that arise |
| 19 |
in the context of big data analytics. Nevertheless there is still room for |
| 20 |
improvement in terms of the support for data management tasks that arise in the |
| 21 |
social sciences, especially when it comes to handling data that come from social |
| 22 |
surveys and opinion surveys. The main reason for this is that the way that |
| 23 |
questionnaire item responses as they are usually coded in machine-readable |
| 24 |
survey data sets do not directly and easily translate into R's data types for |
| 25 |
numeric and categorical data, that is, numerical vectors and factors. As a |
| 26 |
consequence, many social scientists exercise their everyday data management |
| 27 |
tasks with commercial software packages such as SPSS or Stata, but there may be |
| 28 |
social scientists who either cannot afford such commercial software or prefer to |
| 29 |
use, out of principle, open-source software for all steps of data management and |
| 30 |
analysis. |
| 31 |
|
| 32 |
It is one of the aim of the "memisc" package to provide a bridge between social |
| 33 |
science data sets of variables that contain coded responses to questionnaire |
| 34 |
items, with their typical structures involving labelled numeric response codes |
| 35 |
and numeric codes declared as "missing values". As an illustrative example, |
| 36 |
suppose in a pre-election survey, respondents are asked about which party they |
| 37 |
are going to vote for in their constituency in the framework of a |
| 38 |
first-past-the-post electoral system. Suppose the response categories offered to |
| 39 |
the respondents are "Conservative", "Labour", "Liberal Democrat", "Other |
| 40 |
party".[^1] A survey agency that actually conducts the interviews with a sample |
| 41 |
of voters may, according to common practice, use the following codes to collect |
| 42 |
the responses to the question about the vote intention: |
| 43 |
|
| 44 |
<div class="booktable"> |
| 45 |
<style> |
| 46 |
.booktable table th { |
| 47 |
border-top: 0 none; |
| 48 |
border-bottom: 0 none; |
| 49 |
background-color: unset; |
| 50 |
} |
| 51 |
.booktable table td { |
| 52 |
border-top: 0 none; |
| 53 |
border-bottom: 0 none; |
| 54 |
background-color: unset; |
| 55 |
} |
| 56 |
|
| 57 |
.booktable table tr.even { |
| 58 |
background-color: unset; |
| 59 |
} |
| 60 |
|
| 61 |
.booktable table tr.header { |
| 62 |
border-top: 2px solid; |
| 63 |
border-bottom: 1px solid; |
| 64 |
} |
| 65 |
|
| 66 |
.booktable table tbody tr:last-child { |
| 67 |
border-bottom: 2px solid; |
| 68 |
} |
| 69 |
</style> |
| 70 |
|
| 71 |
Response category Code |
| 72 |
-------------------- ----- ----- |
| 73 |
Conservative 1 |
| 74 |
Labour 2 |
| 75 |
Liberal Democrat 3 |
| 76 |
Other Party 4 |
| 77 |
Will not vote 9 |
| 78 |
Don't know 97 (M) |
| 79 |
Answer refused 98 (M) |
| 80 |
Not applicable 99 (M) |
| 81 |
|
| 82 |
</div> |
| 83 |
|
| 84 |
In data sets that contain the results of such coding are essentially numeric |
| 85 |
data -- with some additional information about the "value labels" (the labels |
| 86 |
attached to the numeric values) and about the "missing values" (those numeric |
| 87 |
values that indicate responses that one usually does not want to include into |
| 88 |
statistical analysis). While this coding frame for responses to survey |
| 89 |
questionnaires is far from uncommon in the social sciences, it is not |
| 90 |
straightforward to retain this information in *R* objects. Here there are two |
| 91 |
main alternatives, (1) one could store the responses as a numeric vector, |
| 92 |
thereby losing the information about the labelled values, or (2) one could store |
| 93 |
the responses as a factor, thereby losing the information contained in the |
| 94 |
codes. Either way, one will lose the information about the "missing values". Of |
| 95 |
course, one can filter out these missing values before data analysis by |
| 96 |
replacing them with `NA`, but it would convenient to have facilities that do |
| 97 |
that automatically. |
| 98 |
|
| 99 |
[^1]: Those familiar with British politics will realise that this is a |
| 100 |
simplification of the menu of available choices that voters in England |
| 101 |
typically face in an election of the House of Commons. |
| 102 |
|
| 103 |
# Standard attributes of survey items |
| 104 |
|
| 105 |
The "memisc" package introduces a new data type (more correctly an `S4` class) |
| 106 |
that allows to handle such data, that allows to adjust labels or missing values |
| 107 |
definitions and to translate such data as needed either into numeric vectors of |
| 108 |
factors, thereby automatically filtering out the missing values. This data time |
| 109 |
(or `S4` class) is, for lack of a better term, called `"item"`. In general, |
| 110 |
users do not bother with the construction of such item vectors. Usually they are |
| 111 |
generated when data sets are imported from data files in SPSS or Stata |
| 112 |
format. This page is mainly concerned with describing the structure of such item |
| 113 |
vectors and how they can be manipulated in the data management step that usually |
| 114 |
precedes data analysis. It is thus possible to do all the data management in *R* |
| 115 |
from importing the pristine data obtained from data archives or other data |
| 116 |
providers, such as the survey institutes to which a principal investigator has |
| 117 |
delegated data collection. Of course, the facilities introduced by the `"item"` |
| 118 |
data type also allow to create appropriate representations of survey item |
| 119 |
responses if a principal investigator obtains only raw numeric codes. In the |
| 120 |
following, the construction of `"item"` vectors from raw numeric data is mainly |
| 121 |
used to highlight their structure. |
| 122 |
|
| 123 |
## Value labels {#value_labels} |
| 124 |
|
| 125 |
```{r,echo=FALSE} |
| 126 |
set.seed(20) |
| 127 |
vote.probs <- c(.361,.29,.23,1-.361-.29-.23) |
| 128 |
decis.probs <- c(vote.probs*.651,1-.651) |
| 129 |
all.probs <- c(.9*decis.probs,.1*rep(1/3,3)) |
| 130 |
voteint <- sample(c(1:4,9,97,98,99), |
| 131 |
prob=all.probs, |
| 132 |
replace=TRUE, |
| 133 |
size=200) |
| 134 |
library(memisc) |
| 135 |
``` |
| 136 |
Suppose a numeric vector of responses to the question about their vote intention coded using |
| 137 |
the coding frame shown above looks as follows |
| 138 |
```{r} |
| 139 |
voteint |
| 140 |
``` |
| 141 |
|
| 142 |
This numeric vector is transformed into an `"item"` vector by attaching labels |
| 143 |
to the codes. The *R* code to attach labels that reflect the coding frame shown |
| 144 |
above may look like follows (if formatted nicely): |
| 145 |
|
| 146 |
```{r} |
| 147 |
# This is to be run *after* memisc has been loaded. |
| 148 |
labels(voteint) <- c(Conservative = 1, |
| 149 |
Labour = 2, |
| 150 |
"Liberal Democrat" = 3, # We have whitespace in the label, |
| 151 |
"Other Party" = 4, # so we need quotation marks |
| 152 |
"Will not vote" = 9, |
| 153 |
"Don't know" = 97, |
| 154 |
"Answer refused" = 98, |
| 155 |
"Not applicable" = 99) |
| 156 |
``` |
| 157 |
`voteint` is now an item vector, for which a particular `"show"` method is defined: |
| 158 |
```{r} |
| 159 |
class(voteint) |
| 160 |
str(voteint) |
| 161 |
voteint |
| 162 |
``` |
| 163 |
|
| 164 |
Like with factors, if *R* shows the contents of the vector, the labels are shown |
| 165 |
(instead of the codes). Since item vectors typically are quite long, because |
| 166 |
they come from interviewing a survey sample and usual survey sample sizes are |
| 167 |
about 2000, we usually do not want to see all the values in the |
| 168 |
vector. `"memisc"` anticipates this and shows at most a single line of |
| 169 |
output. (In the output, also the "level of measurement" is shown, which at this |
| 170 |
point does not have a consquence. It will become clear later what the |
| 171 |
implications of the "level of measurement" are.) |
| 172 |
|
| 173 |
In line with the usual semantics `labels(voteint)` will now show us a |
| 174 |
description of the labels and to which values they are assigned: |
| 175 |
|
| 176 |
```{r} |
| 177 |
labels(voteint) |
| 178 |
``` |
| 179 |
Now if we rather want shorter labels, we can change them either by something like `labels(voteint) <- ...` or by changing the labels using `relabel()`: |
| 180 |
```{r} |
| 181 |
voteint <- relabel(voteint, |
| 182 |
"Conservative" = "Cons", |
| 183 |
"Labour" = "Lab", |
| 184 |
"Liberal Democrat" = "LibDem", |
| 185 |
"Other Party" = "Other", |
| 186 |
"Will not vote" = "NoVote", |
| 187 |
"Don't know" = "DK", |
| 188 |
"Answer refused" = "Refused", |
| 189 |
"Not applicable" = "N.a.") |
| 190 |
``` |
| 191 |
Let us take a look at the result: |
| 192 |
```{r} |
| 193 |
labels(voteint) |
| 194 |
voteint |
| 195 |
str(voteint) |
| 196 |
``` |
| 197 |
|
| 198 |
## Missing values {#missing_values} |
| 199 |
|
| 200 |
In the coding plan shown above, the values 97, 98, and 99 are marked as "missing |
| 201 |
values", that is, while they represent coded responses, they are not to be |
| 202 |
considered as valid in the sense of providing information about the respondent's |
| 203 |
vote intention. For the statistical analysis of vote intention it is natural to |
| 204 |
replace them by `NA`. Yet replacing codes 97, 98, and 99 already at the stage of |
| 205 |
importing data into *R* memory would mean a loss of potentially precious |
| 206 |
information since it precludes, e.g. the motivation to refuse responding to the |
| 207 |
vote intention question or the antencedents of undecidedness. Hence it is better |
| 208 |
to mark those values and to delay their replacement by `NA` to a later stage in |
| 209 |
the analysis of vote intentions and to be able to undo or change the |
| 210 |
"missingness" of these values. For example, not only may one be interested in |
| 211 |
the antecedents of response refusals but also be interested to analyse vote |
| 212 |
intention with non-voting excluded or included. The memisc package provides, |
| 213 |
like SPSS and PSPP, facilities to mark particular values of an item vector as |
| 214 |
"missing" and change such designations throughout the data preperation stage. |
| 215 |
|
| 216 |
There are several ways with `"memisc"` to make distinctions between valid and |
| 217 |
missing values. The first way that mirrors the way it is done in SPSS. To |
| 218 |
illustrate this we return to the fictitious vote intention example. The values |
| 219 |
97,98,99 of `voteint` are designated as "missing" by |
| 220 |
|
| 221 |
```{r} |
| 222 |
missing.values(voteint) <- c(97,98,99) |
| 223 |
``` |
| 224 |
|
| 225 |
The missing values are reflected in the output of `voteint`, (labels of) missing |
| 226 |
values are marked with `*` in the output: |
| 227 |
|
| 228 |
```{r} |
| 229 |
voteint |
| 230 |
``` |
| 231 |
|
| 232 |
It is also possible to extend the set of missing values: We add another value to |
| 233 |
the set of missing values. |
| 234 |
|
| 235 |
```{r} |
| 236 |
missing.values(voteint) <- missing.values(voteint) + 9 |
| 237 |
``` |
| 238 |
The missing values can be recalled as usual: |
| 239 |
```{r} |
| 240 |
missing.values(voteint) |
| 241 |
``` |
| 242 |
The missing values are turned into `NA` if `voteint` is coerced into a numeric vector or a factor, which is what usually happens before the eventual statistical analysis: |
| 243 |
|
| 244 |
```{r} |
| 245 |
as.numeric(voteint)[1:30] |
| 246 |
as.factor(voteint)[1:30] |
| 247 |
``` |
| 248 |
It is also possible to drop all missing value designations: |
| 249 |
```{r} |
| 250 |
missing.values(voteint) <- NULL |
| 251 |
missing.values(voteint) |
| 252 |
as.numeric(voteint)[1:30] |
| 253 |
``` |
| 254 |
In contrast to SPSS it is possible with `"memisc"` to designate the valid, i.e. non-missing values: |
| 255 |
```{r} |
| 256 |
valid.values(voteint) <- 1:4 |
| 257 |
valid.values(voteint) |
| 258 |
missing.values(voteint) |
| 259 |
``` |
| 260 |
Instead of individual valid or missing values it is also possible to define a *range* of values as valid: |
| 261 |
```{r} |
| 262 |
valid.range(voteint) <- c(1,9) |
| 263 |
missing.values(voteint) |
| 264 |
``` |
| 265 |
|
| 266 |
## Other attributes of survey items {#annotations} |
| 267 |
Other software packages targeted at social scientists also allow to add |
| 268 |
annotations to the variables in a data set, which are not subject to the |
| 269 |
syntactic constraints of variable names. These annotations are usually called |
| 270 |
"variable labels" in these software packages. In `"memisc"` the corresponding |
| 271 |
term is "description". In continuation of the running example, we add a |
| 272 |
description to the vote intention variable: |
| 273 |
|
| 274 |
```{r} |
| 275 |
description(voteint) <- "Vote intention" |
| 276 |
description(voteint) |
| 277 |
``` |
| 278 |
|
| 279 |
In contrast to other software, `"memisc"` allows to attach arbitrarily |
| 280 |
annotation to survey items, such as the wording of a survey question: |
| 281 |
|
| 282 |
```{r} |
| 283 |
wording(voteint) <- "Which party are you going to vote for in the general election next Tuesday?" |
| 284 |
wording(voteint) |
| 285 |
annotation(voteint) |
| 286 |
annotation(voteint)["wording"] |
| 287 |
``` |
| 288 |
|
| 289 |
## Codebooks of survey items |
| 290 |
|
| 291 |
It is common in survey research to describe a data set in the form of a |
| 292 |
*codebook*. A codebook summarises each variable in the data set in terms of its |
| 293 |
relevant attributes, that is, the label attached to the variable (in the context |
| 294 |
of the `memisc` package this is called its "description"), the labels attached |
| 295 |
to the values of the variable, which values of the variable are supposed to be |
| 296 |
*missing* or *valid*, as well as univariate summary statistics of each variable, |
| 297 |
usually without and with missing variables included. Such functionality is |
| 298 |
provided in this package by the function `codebook()`. `codebook()` when applied |
| 299 |
to an `"item"` object returns a `"codebook"` object, which when printed to the |
| 300 |
console gives an overview of the variable usually required for the codebook of a |
| 301 |
data set (the production of codebooks for whole data sets is described further |
| 302 |
below). To illustrate the `codebook()` function we now produce a codebook of the |
| 303 |
`voteint` item variable created above: |
| 304 |
|
| 305 |
```{r} |
| 306 |
codebook(voteint) |
| 307 |
``` |
| 308 |
|
| 309 |
As can be seen in the output, the `codebook()` function reports the name of the |
| 310 |
variable, the description (if defined for the variable), and the question |
| 311 |
wording (again if defined). Further it reports the storage mode (which is use by |
| 312 |
*R*), the level of measurement ("nominal", "ordinal", "interval", or "ratio") |
| 313 |
and the range of valid values (or alternatively, individually defined valid |
| 314 |
values, individually defined missing values, or ranges of missing values). For |
| 315 |
item variables with value labels, it shows a table of frequencies of the |
| 316 |
labelled values, and the percentages of valid values and all values with |
| 317 |
missings included. |
| 318 |
|
| 319 |
Codebooks are particularly useful to find "wild codes", that is codes that are |
| 320 |
not labelled, and usually produced by coding errors. Such coding errors may be |
| 321 |
less common in data sets produced by CAPI or CATI or online surveys, but they |
| 322 |
may occur in older data sets from before the age of computer-assisted |
| 323 |
interviewing and also during the course of data management. This use of |
| 324 |
codebooks is demonstrated in the following by deliberatly adding some coding |
| 325 |
errors into a copy of our `voteint` variable: |
| 326 |
|
| 327 |
```{r} |
| 328 |
voteint1 <- voteint |
| 329 |
voteint1[sample(length(voteint),size=20)] <- c(rep(5,13),rep(7,7)) |
| 330 |
``` |
| 331 |
|
| 332 |
The presence of these "wild codes" can now be spotted using `codebook()`: |
| 333 |
|
| 334 |
```{r} |
| 335 |
codebook(voteint1) |
| 336 |
``` |
| 337 |
|
| 338 |
The output shows that 20 observations contain wild codes in this variable. Why |
| 339 |
don't we get a list of wild codes as part of the codebook? The reason is that |
| 340 |
codebook is supposed also to work with continuous variables that have thousands |
| 341 |
of unique, unlabelled values. Users certainly will not like to see them all as |
| 342 |
part of a codebook. |
| 343 |
|
| 344 |
In order to get a list of wild codes the development version of "memisc" |
| 345 |
contains the function `wild.codes()`, which we apply to the variable `voteint1` |
| 346 |
|
| 347 |
```{r} |
| 348 |
wild.codes(voteint1) |
| 349 |
``` |
| 350 |
|
| 351 |
We see that 6.5 and 3.5 percent of the observations have the wild codes 5 and 7. |
| 352 |
|
| 353 |
To see how `codebook()` works with variables without value labels, we create an |
| 354 |
unlabelled copy of our `voteint` variable: |
| 355 |
|
| 356 |
```{r} |
| 357 |
voteint2 <- voteint |
| 358 |
labels(voteint2) <- NULL # This deletes all value labels |
| 359 |
codebook(voteint2) |
| 360 |
``` |
| 361 |
|
| 362 |
Usually, variables without labelled values represent measures on an interval or |
| 363 |
ratio scale. In that case, we do not want to see how many unlabelled values |
| 364 |
there are, but we want to get some other statistics, such as mean, variance, |
| 365 |
etc. To this purpose, we decleare the variable `voteint2` to have an |
| 366 |
interval-scale level of measurement.[^2] |
| 367 |
|
| 368 |
```{r} |
| 369 |
measurement(voteint2) <- "interval" |
| 370 |
codebook(voteint2) |
| 371 |
``` |
| 372 |
[^2]: Of course, substantially it does not make sense at all to form averages |
| 373 |
etc. of voting choices, so "do not try this at home". This example is merely |
| 374 |
to demonstrate codebooks and the setting of scale-levels. |
| 375 |
|
| 376 |
For convenience of including them into word-processor documents, there is also |
| 377 |
the possibility to export codebooks into HTML: |
| 378 |
|
| 379 |
```{r,results='asis'} |
| 380 |
show_html(codebook(voteint)) |
| 381 |
``` |
| 382 |
|
| 383 |
# Data sets: Containers of survey items |
| 384 |
|
| 385 |
Usually one expects to be able handle data on responses to survey items not in |
| 386 |
isolation, but as part of a data set, which contains a multitude of observations |
| 387 |
on many variables. The usual data structure in *R* to contain |
| 388 |
observation-on-variables data is the *data frame*. In principle it is possible |
| 389 |
to put survey item vectors as described above into a data frame, nevertheless |
| 390 |
the `"memisc"` package provides a special data structure to contain survey item |
| 391 |
data called data sets or data set-objects, that is, objects of class |
| 392 |
`"data.set"`. This opens up the possibility to automatically translate survey |
| 393 |
items into regular vectors and factors, as expected by typical data analysis |
| 394 |
functions, such as `lm()` or `glm()`. |
| 395 |
|
| 396 |
## The structure of `"data.set"` objects |
| 397 |
|
| 398 |
Data set objects have essentially the same row-by-column structure as data |
| 399 |
frames: They are a set of vectors (however of class `"item"`) all with the same |
| 400 |
length, so that in each row of the data set there are values in these vectors. |
| 401 |
Observations can be addressed as rows of a `"data.set"` and variabels can be |
| 402 |
addressed as columns, just as one may used to with regards to data frames. Most |
| 403 |
data management operations that you can do with data frames can also be done |
| 404 |
with data sets (such as merging them or using the functions `with()` or |
| 405 |
`within()`). Yet in contrast to data frames, data sets are always expected to |
| 406 |
contain objects of class `"item"`, and any vectors or factors from which a |
| 407 |
`"data.set"` object is constructed are changed into `"item"` objects. |
| 408 |
|
| 409 |
Another difference is the way that `"data.set"` objects are shown on the |
| 410 |
console. As `S4` objects, if a user types in the name of a `"data.set"` objects, |
| 411 |
the function `show()` (and not `print()`) is applied to it. The `show()`-method |
| 412 |
for data set objects is defined in such a way that only the first few |
| 413 |
observations of the first few variables are shown on the console -- in contrast |
| 414 |
to `print()` as applied to a data frame, which shows *all* observations on *all* |
| 415 |
variables. While it may be intuitive and convenient to be shown all observations |
| 416 |
in a small data frame, this is not what you will want if your data set contains |
| 417 |
more than 2000 observations on several hundred variables, the dimensions that |
| 418 |
typical social science data sets have that you can download from data archives |
| 419 |
such as that of ICPSR or GESIS. |
| 420 |
|
| 421 |
The main facilitites of `"data.set"` objects are demonstrated in what follows. |
| 422 |
First, we create a data set with fictional survey responses |
| 423 |
```{r} |
| 424 |
Data <- data.set( |
| 425 |
vote = sample(c(1,2,3,4,8,9,97,99), |
| 426 |
size=300,replace=TRUE), |
| 427 |
region = sample(c(rep(1,3),rep(2,2),3,99), |
| 428 |
size=300,replace=TRUE), |
| 429 |
income = round(exp(rnorm(300,sd=.7))*2000) |
| 430 |
) |
| 431 |
``` |
| 432 |
Then, we take a look at this already sizeable `"data.set"`" object: |
| 433 |
```{r} |
| 434 |
Data |
| 435 |
``` |
| 436 |
|
| 437 |
In this case, our data set has only three variables, all of which are shown, but |
| 438 |
of the observations we see only the first 25. Actually the number of |
| 439 |
observations shown can be determined by the option `"show.max.obs"` which |
| 440 |
defaults to 25, but can be changed as convenient: |
| 441 |
|
| 442 |
```{r} |
| 443 |
options(show.max.obs=5) |
| 444 |
Data |
| 445 |
# Back to the default |
| 446 |
options(show.max.obs=25) |
| 447 |
``` |
| 448 |
If you *really* want to see the complete data on your console, then you can use `print()` instead: |
| 449 |
```{r,eval=FALSE} |
| 450 |
print(Data) |
| 451 |
``` |
| 452 |
but you should not do this with large data sets, such as the Eurobarometer trend file ... |
| 453 |
|
| 454 |
## Manipulating data in data sets |
| 455 |
|
| 456 |
Typical data management tasks that you would otherwise have done in commercial packages like SPSS or |
| 457 |
Stata can be conducted within data set objects. Actually to provide this possibility (to the author |
| 458 |
of the package) was the main reason that the `"memisc"` package was created. |
| 459 |
To demonstrate this, we continue with our fictional data which we prepare for further analysis: |
| 460 |
```{r} |
| 461 |
Data <- within(Data,{ |
| 462 |
description(vote) <- "Vote intention" |
| 463 |
description(region) <- "Region of residence" |
| 464 |
description(income) <- "Household income" |
| 465 |
wording(vote) <- "If a general election would take place next Tuesday, |
| 466 |
the candidate of which party would you vote for?" |
| 467 |
wording(income) <- "All things taken into account, how much do all |
| 468 |
household members earn in sum?" |
| 469 |
foreach(x=c(vote,region),{ |
| 470 |
measurement(x) <- "nominal" |
| 471 |
}) |
| 472 |
measurement(income) <- "ratio" |
| 473 |
labels(vote) <- c( |
| 474 |
Conservatives = 1, |
| 475 |
Labour = 2, |
| 476 |
"Liberal Democrats" = 3, |
| 477 |
"Other" = 4, |
| 478 |
"Don't know" = 8, |
| 479 |
"Answer refused" = 9, |
| 480 |
"Not applicable" = 97, |
| 481 |
"Not asked in survey" = 99) |
| 482 |
labels(region) <- c( |
| 483 |
England = 1, |
| 484 |
Scotland = 2, |
| 485 |
Wales = 3, |
| 486 |
"Not applicable" = 97, |
| 487 |
"Not asked in survey" = 99) |
| 488 |
foreach(x=c(vote,region,income),{ |
| 489 |
annotation(x)["Remark"] <- "This is not a real survey item, of course ..." |
| 490 |
}) |
| 491 |
missing.values(vote) <- c(8,9,97,99) |
| 492 |
missing.values(region) <- c(97,99) |
| 493 |
|
| 494 |
# These to variables do not appear in the |
| 495 |
# the resulting data set, since they have the wrong length. |
| 496 |
junk1 <- 1:5 |
| 497 |
junk2 <- matrix(5,4,4) |
| 498 |
|
| 499 |
}) |
| 500 |
``` |
| 501 |
|
| 502 |
Now that we have added information to the data set that reflects the code plan |
| 503 |
of the variables, we take a look how the it looks like: |
| 504 |
|
| 505 |
```{r} |
| 506 |
Data |
| 507 |
``` |
| 508 |
|
| 509 |
As you can see, labelled item look a bit like factors, but with a difference: |
| 510 |
User-defined missing values are marked with an asterisk. |
| 511 |
|
| 512 |
Subsetting a data set object works as expected: |
| 513 |
```{r} |
| 514 |
EnglandData <- subset(Data,region == "England") |
| 515 |
EnglandData |
| 516 |
``` |
| 517 |
|
| 518 |
|
| 519 |
## Codebooks of data sets {#codebooks} |
| 520 |
|
| 521 |
Previouly, we created a code book for individual survey items. But it is also |
| 522 |
possible to create a codebook for a whole data set (what one usually wants to |
| 523 |
have a codebook of). Obtaining a codebook is simple, by applying the function |
| 524 |
`codebook()` to the data frame: |
| 525 |
|
| 526 |
```{r} |
| 527 |
codebook(Data) |
| 528 |
``` |
| 529 |
On a website, it looks better in HTML: |
| 530 |
```{r,results='asis'} |
| 531 |
show_html(codebook(Data)) |
| 532 |
``` |
| 533 |
|
| 534 |
## Translating data sets into data frames |
| 535 |
|
| 536 |
The punchline of the existence of `"data.set"` objects however is that they can |
| 537 |
be coerced into regular data frames, using `as.data.frame()`, which causes |
| 538 |
survey items to be translated into regular numeric vectors or factors using |
| 539 |
`as.numeric()`, `as.factor()` or `as.ordered()` as above, and pre-determined |
| 540 |
missing values changed into `NA`. Whether a survey item is changed into a |
| 541 |
numerical vector, an unordered or an ordered factor depends on the declared |
| 542 |
measurement level (which can be manipulated by `measurement()` as shown above). |
| 543 |
|
| 544 |
In the example developed so far, the variables `vote` and `region` are declared |
| 545 |
to have a nominal level of measurement, while `income` is declared to have a |
| 546 |
ratio scale. That is, in statistical analyses, we want the first two variables |
| 547 |
to be handled as (unordered) factors, and the income variable as a numerical |
| 548 |
vector. In addition, we want all the user-declared missing values to be changed |
| 549 |
into `NA` so that observations where respondents stated to "don't know" what |
| 550 |
they are goint go vote for are excluded from the analysis. So let's see whether |
| 551 |
this works - we coerce our data set into a data frame: |
| 552 |
|
| 553 |
```{r} |
| 554 |
DataFr <- as.data.frame(Data) |
| 555 |
## Looking a the data frame structure |
| 556 |
str(DataFr) |
| 557 |
## Looking at the first 25 observations |
| 558 |
DataFr[1:25,] |
| 559 |
``` |
| 560 |
|
| 561 |
Indeed the translation works as expected, so we can use it for statistical |
| 562 |
analysis, here a simple cross tab: |
| 563 |
|
| 564 |
```{r} |
| 565 |
xtabs(~vote+region,data=DataFr) |
| 566 |
``` |
| 567 |
|
| 568 |
In fact, since many functions such as `xtabs()`, `lm()`, `glm()`, etc. coerce |
| 569 |
theire `data=` argument into a data frame, an explicit coercion with |
| 570 |
`as.data.frame()` is not always needed: |
| 571 |
|
| 572 |
```{r} |
| 573 |
xtabs(~vote+region,data=Data) |
| 574 |
``` |
| 575 |
Sometimes we do want missing values to be included, and this is possible too: |
| 576 |
```{r} |
| 577 |
xtabs(~vote+region,data=within(Data, |
| 578 |
vote <- include.missings(vote))) |
| 579 |
``` |
| 580 |
|
| 581 |
For convenience, there is also a codebook method for data frames: |
| 582 |
```{r,results='asis'} |
| 583 |
show_html(codebook(DataFr)) |
| 584 |
``` |
| 585 |
|
| 586 |
# More tools for data preparation |
| 587 |
|
| 588 |
When social scientists work with survey data, these are not always organised and |
| 589 |
coded in a way that suits the intended data analysis. For this reasons, the |
| 590 |
`"memisc"` package provides the two functions `recode()` and `cases()`. The |
| 591 |
former is -- as the name suggests -- for recoding, while the second allows for |
| 592 |
complex distinctions of cases and can be seen as a more general version of |
| 593 |
`ifelse()`. These two functions are demonstrated with a "real-life" example. |
| 594 |
|
| 595 |
## Recoding {#recode} |
| 596 |
|
| 597 |
The function `recode()` is similar in semantics to the function of the same name |
| 598 |
in package [`"car"`][CAR] and designed in such a way that it does not conflict |
| 599 |
with this function. In fact, if `recode()` is called in the way as expected in |
| 600 |
package `"car"`, it will dispatch processing to this function. In other words, |
| 601 |
users of this other package may use `recode()` as they are used to. The version |
| 602 |
of the `recode()` function provided by `"memisc"` differs from the `"car"` |
| 603 |
version in so far as its syntax is more R-ish (or so I believe). |
| 604 |
|
| 605 |
[CAR]: https://cran.r-project.org/package=car |
| 606 |
|
| 607 |
Here we load an example data set -- a subset of the German Longitudinal Election |
| 608 |
Study for 2013[^3] -- into R's memory. |
| 609 |
|
| 610 |
```{r} |
| 611 |
load(system.file("gles/gles2013work.RData",package="memisc")) |
| 612 |
``` |
| 613 |
|
| 614 |
As a simple example for the use of `recode()` we use this function to recode |
| 615 |
German Bundesländer into an item with two values or East and West Germany. But |
| 616 |
first we create a codebook for the variable that contains the Bundesländer |
| 617 |
codes: |
| 618 |
|
| 619 |
```{r,results='asis'} |
| 620 |
with(gles2013work, |
| 621 |
show_html(codebook(bula))) |
| 622 |
``` |
| 623 |
We now recode the Bundesländer codes into a new variable: |
| 624 |
```{r} |
| 625 |
gles2013work <- within(gles2013work, |
| 626 |
east.west <- recode(bula, |
| 627 |
East = 1 <- c(3,4,8,13,14,16), |
| 628 |
West = 2 <- c(1,2,5:7,9:12,15) |
| 629 |
)) |
| 630 |
``` |
| 631 |
and check whether this was successful: |
| 632 |
```{r} |
| 633 |
xtabs(~bula+east.west,data=gles2013work) |
| 634 |
``` |
| 635 |
as can be seen, `recode()` was called in such a way that not only old |
| 636 |
codes are transferred into new ones, but also the new codes are labelled. |
| 637 |
|
| 638 |
|
| 639 |
[^3]: The [German Longitudinal Election |
| 640 |
Study](https://www.gesis.org/gles/about-gles) is funded by the German National |
| 641 |
Science Foundation (DFG) and carried out outin close cooperation with the |
| 642 |
[DGfW](https://www.dgfw.info/), German Society for Electoral Studies. Principal |
| 643 |
investigators are Hans Rattinger (University of Mannheim, until 2014), Sigrid |
| 644 |
Roßteutscher (University of Frankfurt), Rüdiger Schmitt-Beck (University of |
| 645 |
Mannheim), Harald Schoen (Mannheim Centre for European Social Research, from |
| 646 |
2015), Bernhard Weßels (Social Science Research Center Berlin), and Christof |
| 647 |
Wolf (GESIS – Leibniz Institute for the Social Sciences, since 2012). Neither |
| 648 |
the funding organisation nor the principal investigators bear any responsibility |
| 649 |
for the example code shown here. |
| 650 |
|
| 651 |
## Case distinctions |
| 652 |
|
| 653 |
Recoding can be used to combine the codes of an item into a smaller set, but |
| 654 |
sometimes one needs to do more complex data preparations, in which the values of |
| 655 |
some variable are set conditional on values of another one, etc. For such |
| 656 |
tasks, the `"memisc"` package provides the function `cases()`. This function |
| 657 |
takes several expressions that evaluate to logical vectors as arguments and |
| 658 |
returns a numeric vector or a factor, the values or level of which indicate for |
| 659 |
each observation which of the expressions evaluates to `TRUE` the respective |
| 660 |
observation. The factor levels are named after the logical expressions. A simple |
| 661 |
example looks thus: |
| 662 |
|
| 663 |
```{r} |
| 664 |
x <- 1:10 |
| 665 |
xc <- cases(x <= 3, |
| 666 |
x > 3 & x <= 7, |
| 667 |
x > 7) |
| 668 |
data.frame(x,xc) |
| 669 |
``` |
| 670 |
In this example `cases()` returns a factor. It can also be made to return a numeric value: |
| 671 |
```{r} |
| 672 |
xn <- cases(1 <- x <= 3, |
| 673 |
2 <- x > 3 & x <= 7, |
| 674 |
3 <- x > 7) |
| 675 |
data.frame(x,xn) |
| 676 |
``` |
| 677 |
|
| 678 |
This example shows the way `cases()` works in the abstract. How this can be made |
| 679 |
used of in practical example is best demonstrated by a real-world example, again |
| 680 |
using data from the German Longitudinal Election Study. |
| 681 |
|
| 682 |
In the 2013 election module, the intention to vote during the pre-election of |
| 683 |
respondents interviewed in the pre-election wave (`wave==1`) and the |
| 684 |
participation in the election of respondents interviewed in the post-election |
| 685 |
wave (`wave==2`) are recorded in different data set variables, named here |
| 686 |
`intent.turnout` and `turnout`. The variable `intent.voteint` has codes for |
| 687 |
whether the respondents were sure to participate (1), were likely to participate |
| 688 |
(2), were undecided (3), likely not to (4), sure not to participate (5), or |
| 689 |
whether they have cast a postal vote (6). Variable `turnout` has codes for those |
| 690 |
who participated in the election (1) or did not (2). |
| 691 |
|
| 692 |
The intention for the candidate vote is recorded in variable `voteint.candidate` |
| 693 |
and the intention for the list vote is recoded in variable `voteint.list` for |
| 694 |
the pre-election wave. A postal vote for party candidate is recorded in |
| 695 |
variable `postal.vote.candidate` and for a party list is in variable |
| 696 |
`postal.vote.list`. Recalled votes in the post-election wave are recorded in |
| 697 |
variables `vote.candidate` and `vote.list`. |
| 698 |
|
| 699 |
These various variables are combined into two variables that has valid values |
| 700 |
for both waves, `candidate.vote` and `list.vote`. For this, several conditions |
| 701 |
have to be handled: whether a respondent is in the pre-election or the |
| 702 |
post-election wave, whether s/he is not likely or sure not to vote, or whether |
| 703 |
she has cast a postal vote. Thus the variable `cases()` is helpful here: |
| 704 |
|
| 705 |
```{r} |
| 706 |
gles2013work <- within(gles2013work,{ |
| 707 |
|
| 708 |
candidate.vote <- cases( |
| 709 |
wave == 1 & intent.turnout == 6 -> postal.vote.candidate, |
| 710 |
wave == 1 & intent.turnout %in% 4:5 -> 900, |
| 711 |
wave == 1 & intent.turnout %in% 1:3 -> voteint.candidate, |
| 712 |
wave == 2 & turnout == 1 -> vote.candidate, |
| 713 |
wave == 2 & turnout == 2 -> 900 |
| 714 |
) |
| 715 |
|
| 716 |
list.vote <- cases( |
| 717 |
wave == 1 & intent.turnout == 6 -> postal.vote.list, |
| 718 |
wave == 1 & intent.turnout %in% 4:5 -> 900, |
| 719 |
wave == 1 & intent.turnout %in% 1:3 -> voteint.list, |
| 720 |
wave == 2 & turnout ==1 -> vote.list, |
| 721 |
wave == 2 & turnout ==2 -> 900 |
| 722 |
) |
| 723 |
}) |
| 724 |
``` |
| 725 |
|
| 726 |
The code shown above does the following: In the pre-election wave (`wave == 1`), |
| 727 |
the `candidate.vote` variable receives the value of the postal vote variable |
| 728 |
`postal.vote.candidate` if a postal vote was cast (`intent.turnout == 6`), it |
| 729 |
receives the value `900` for those respondents who where likely or sure not to |
| 730 |
vote (`intent.turnout %in% 4:5`), and the value of the variable |
| 731 |
`voteint.candidate` for all others (`intent.turnout %in% 1:3`). In the |
| 732 |
post-election wave (`wave == 2`) variable `candidate.vote` receives the value of |
| 733 |
variable `vote.candidate` if the respondent has voted (`turnout == 1`) or the |
| 734 |
value `900` if s/he has not voted (`turnout == 2`). The variable `list.vote` is |
| 735 |
constructed in an analogous manner from the variables `wave`, `intent.turnout`, |
| 736 |
`turnout`, `postal.vote.list`, `voteint.list` and `vote.list`. After the |
| 737 |
constructin, the resulting variables `candidate.vote` and `list.vote` are |
| 738 |
labelled and missing values are declared: |
| 739 |
|
| 740 |
```{r} |
| 741 |
gles2013work <- within(gles2013work,{ |
| 742 |
candidate.vote <- recode(as.item(candidate.vote), |
| 743 |
"CDU/CSU" = 1 <- 1, |
| 744 |
"SPD" = 2 <- 4, |
| 745 |
"FDP" = 3 <- 5, |
| 746 |
"Grüne" = 4 <- 6, |
| 747 |
"Linke" = 5 <- 7, |
| 748 |
"NPD" = 6 <- 206, |
| 749 |
"Piraten" = 7 <- 215, |
| 750 |
"AfD" = 8 <- 322, |
| 751 |
"Other" = 10 <- 801, |
| 752 |
"No Vote" = 90 <- 900, |
| 753 |
"WN" = 98 <- -98, |
| 754 |
"KA" = 99 <- -99 |
| 755 |
) |
| 756 |
list.vote <- recode(as.item(list.vote), |
| 757 |
"CDU/CSU" = 1 <- 1, |
| 758 |
"SPD" = 2 <- 4, |
| 759 |
"FDP" = 3 <- 5, |
| 760 |
"Grüne" = 4 <- 6, |
| 761 |
"Linke" = 5 <- 7, |
| 762 |
"NPD" = 6 <- 206, |
| 763 |
"Piraten" = 7 <- 215, |
| 764 |
"AfD" = 8 <- 322, |
| 765 |
"Other" = 10 <- 801, |
| 766 |
"No Vote" = 90 <- 900, |
| 767 |
"WN" = 98 <- -98, |
| 768 |
"KA" = 99 <- -99 |
| 769 |
) |
| 770 |
|
| 771 |
missing.values(candidate.vote) <- 98:99 |
| 772 |
missing.values(list.vote) <- 98:99 |
| 773 |
measurement(candidate.vote) <- "nominal" |
| 774 |
measurement(list.vote) <- "nominal" |
| 775 |
}) |
| 776 |
``` |
| 777 |
|
| 778 |
Finally, we can get a cross-tabulation of list votes and the East-West factor and |
| 779 |
a cross tabulation of candidate votes against list votes: |
| 780 |
```{r,width=120} |
| 781 |
xtabs(~list.vote+east.west,data=gles2013work) |
| 782 |
xtabs(~list.vote+candidate.vote,data=gles2013work) |
| 783 |
``` |
| 784 |
|