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 Check if a Vector Contains the Given Element
Here we will be using the
%in%
operatormatch()
functionany()
function.
Example 1: Check if Element Exists in R Vector Using %in%
# create two strings
vowel_letters <- c("a", "e", "i", "o", "u")
"a" %in% vowel_letters # TRUE
"s" %in% vowel_letters # FALSE
Output
[1] TRUE
[2] FALSE
In the above example, we have used the %in%
operator to check if an element exists in the vector named vowel_letters.
Here,
"a"
is present in vowel_letters, so the method returnsTRUE
"s"
is not present in vowel_letters, so the method returnsFALSE
Example 2: Check if Element Exists in R Vector Using match()
The match()
function returns a vector position of the element if the element exists. Else the function returns NA
. For example,
# create two strings
vowel_letters <- c("a", "e", "i", "o", "u")
# check if "i" is present in vowel_letters
match("i", vowel_letters) # 3
# check if "p" is present in vowel_letters
match("p", vowel_letters) # NA
Output
[1] 3
[1] NA
In the above example, we have used the match()
function to check if an element exists in the vector named vowel_letters.
Here,
"i"
is present in vowel_letters, so the method returns vector position of element i.e. 3"p"
is not present in vowel_letters, so the method returnsNA
Example 3: Check if Element Exists in R Vector Using any()
# create two strings
languages <- c("R", "Swift", "Java", "Python")
# check if "Swift" is present in languages using any()
any("Swift" == languages) # TRUE
# check if "C" is present in languages using any()
any("C" == languages) # FALSE
Output
[1] TRUE
[2] FALSE
Here, we have used the any()
function to check if an element exists in the vector named languages.
Since
"Swift"
is present in languages, so the method returnsTRUE
"C"
is not present in languages, so the method returnsFALSE