Primary exercises
Dietary intakes.
Four patients had daily dietary intakes of 2314, 2178, 1922, 2004 kcal.
Make a vectorintakesKCal
of these four values.
What is the class of this vector?
Convert the values into in kJ using 1 kcal = 4.184 kJ.Combining (appending) vectors.
Additional set of intakes is provided: 2122, 2616, NA, 1771 kcal.
Usec()
to append the new intakes after values inintakesKCal
and store the result inallIntakesKCal
.
Print the combined vector and print its calculatedlength
.Mean and sum.
Calculatemean
intake for patients in vectorintakesKCal
.
Next, calculatemean
intake for patients in vectorallIntakesKCal
.
Can you explain the result?
Check help for?mean
, in particular thena.rm
argument.
Use the extra argumentna.rm=TRUE
to calculate themean
of non-NA
elements ofallIntakesKCal
.
Check help for?sum
how to omitNA
elements in sum calculation.
Now, calculate the totalsum
ofallIntakesKCal
intakes ignoring theNA
element.Selecting and counting (non)missing elements.
Understand the result ofis.na( allIntakesKCal )
.
Now, negate the above result with!
operator.
Use above vectors as argument tosum
to calculate the number of missing and non-missing elements inallIntakesKCal
.
UnderstandallIntakesKCal[ !is.na( allIntakesKCal ) ]
.Descriptive statistics of a vector; normally distributed random numbers.
The codev <- rnorm( 10 )
would sample 10 numbers from the normal distribution and store them as a vector inv
.
Printv
. Then repeatv <- rnorm( 10 )
and printv
again. Hasv
changed? Printv
and find by eye the smallest and the largest of these numbers.
Try to use the functionsmin
andmax
onv
– have you found the same numbers?
Calculate themean
,median
and the standard deviation (sd
) ofv
.Selecting and counting elements by a condition. Type
v < 0
and understand the result.
How to interpret the number produced bysum( v < 0 )
? How to interpret the number produced bysum( !( v < 0 ) )
?Head and tail.
Often there is a need to quickly look at the beginning (head
) or at the end (tail
) of a vector.
Try these functions to show the first 5 and the last 7 elements of a randomly generated vectorv <- rnorm( 20 )
.