Primary exercises
- Manually created factor.
In a study participants were asked whether their sport activity is
none
, oncePerWeek
, severalPerWeek
or daily
.
Build a proper factor for the responses below and store it in a variable
w
.
Print the factor.
Write the code to count the numbers of occurrences of each level and
print the counts.
severalPerWeek, none, none, oncePerWeek, oncePerWeek, oncePerWeek, oncePerWeek, ?, none, none
- A factor with a random content.
Read help about the function sample
.
Then study and try the following lines of code to understand the
results.
Next, understand why an error is generated and use replace
argument to generate a vector with 100 samples.
Store this vector in a variable v
and build a factor
w
from it.
Finally, count the numbers of occurrences of each level in
w
.
Ensure, that levels are in order provided in the variable
lvs
.
lvs <- c( "none", "oncePerWeek", "severalPerWeek", "daily" )
sample( lvs, 3 )
sample( lvs, 3 )
sample( lvs, 3 )
sample( lvs, 100 )
- Reordering factor levels.
When a factor is shown on an axis of a plot, the order is given by its
levels.
The factor w
from the previous exercise will be then shown
in this order: none
, oncePerWeek
,
severalPerWeek
, daily
.
But for a picture in a manuscript the following order might be needed:
daily
, severalPerWeek
,
oncePerWeek
, none
.
Apply to w
one of the fct_
functions from the
tidyverse
library to produce a factor w2
with
the requested order.
Show the levels of w2
.
Again show the number of elements of each level in w2
and
compare it with the table of the previous exercise.
Copyright © 2023 Biomedical Data Sciences (BDS) | LUMC