Primary exercises
Dietary intakes.
Four patients had daily dietary intakes of 2314, 2178, 1922, 2004 kcal.
Make a vectorintakesKCalof 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 inintakesKCaland store the result inallIntakesKCal.
Print the combined vector and print its calculatedlength.Mean and sum.
Calculatemeanintake for patients in vectorintakesKCal.
Next, calculatemeanintake for patients in vectorallIntakesKCal.
Can you explain the result?
Check help for?mean, in particular thena.rmargument.
Use the extra argumentna.rm=TRUEto calculate themeanof non-NAelements ofallIntakesKCal.
Check help for?sumhow to omitNAelements in sum calculation.
Now, calculate the totalsumofallIntakesKCalintakes ignoring theNAelement.Selecting and counting (non)missing elements.
Understand the result ofis.na( allIntakesKCal ).
Now, negate the above result with!operator.
Use above vectors as argument tosumto 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 printvagain. Hasvchanged? Printvand find by eye the smallest and the largest of these numbers.
Try to use the functionsminandmaxonv– have you found the same numbers?
Calculate themean,medianand the standard deviation (sd) ofv.Selecting and counting elements by a condition. Type
v < 0and 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 ).