Course
Data Frames
Convert a List to a DataframeCreate an Empty DataframeCombine Two Dataframe into OneChange Column Name of a DataframeExtract Columns From a DataframeDrop Columns in a DataframeReorder Columns in a DataframeSplit DataframeMerge Multiple DataframesDelete Rows From DataframeMake a List of DataframesIntroduction
"Hello World" ProgramAdd Two VectorsFind Sum, Mean and Product of Vector in R ProgrammingTake Input From UserGenerate Random Number from Standard DistributionsSample from a PopulationFind Minimum and MaximumSort a VectorStrings
Concatenate Two StringsFind the Length of a StringCheck if Characters are Present in a StringExtract n Characters From a StringReplace Characters in a StringCompare two StringsConvert Factors to CharactersTrim Leading and Trailing WhitespacesVectors
Concatenate a Vector of StringsCheck if a Vector Contains the Given ElementCount the Number of Elements in a VectorFind Index of an Element in a VectorAccess Values in a VectorAdd Leading Zeros to VectorR Program to Sample from a Population
We generally require to sample data from a large population.
R has a function called sample()
to do the same. We need to provide the population and the size we wish to sample.
Additionally, we can specify if we want to do sampling with replacement. By default it is done without replacement.
Example: Sample From a Population
Sample 2 items from x
> x
[1] 1 3 5 7 9 11 13 15 17
> # sample 2 items from x
> sample(x, 2)
[1] 13 9
If we don’t provide the size to sample, it defaults to the length of the population. This can be used to scramble x.
More examples to sample from a population.
> # sample with replacement
> sample(x, replace = TRUE)
[1] 15 17 13 9 5 15 11 15 1
> # if we simply pass in a positive number n, it will sample
> # from 1:n without replacement
> sample(10)
[1] 2 4 7 9 1 3 10 5 8 6
An example to simulate a coin toss for 10 times.
> sample(c("H","T"),10, replace = TRUE)
[1] "H" "H" "H" "T" "H" "T" "H" "H" "H" "T"