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 Add Leading Zeros to Vector
Example 1: Using paste0() to add Leading Zeros to R Vectors
employee_id <- c(11, 12, 13, 14)
# add leading zeros
result <- paste0("0", employee_id)
print(result)
Output
[1] "011" "012" "013" "014"
In the above example, we have used the paste0()
function to add zero at the beginning of each vector element.
paste0("0", employee_id)
Here, inside paste0()
we have passed,
"0"
- number of leading zeros we want to add- employee_id - the name of the vector
Example 2: Using sprintf() to add Leading Zeros to R Vectors
employee_id <- c(11, 12, 13, 14)
# add leading zeros
sprintf("%004d", employee_id)
Output
[1] "0011" "0012" "0013" "0014"
Here, we have passed the sprintf()
function to add 2 zeros at the beginning of each vector element.
The formatting code %004d
inside sprintf()
means add 2 leading zeros and format vector elements as an integer of width 4.