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 Extract Columns From a Dataframe
There are different ways to extract columns from a data frame in R:
- using index value
- column name
- using
$
to access specific column
Example 1: Use Index Value to Access Dataframe Column in R
# Create a data frame
dataframe1 <- data.frame (
Name = c("Juan", "Alcaraz", "Simantha"),
Age = c(22, 15, 19),
Vote = c(TRUE, FALSE, TRUE)
)
# pass index value 1 to access first column
print(dataframe1[1])
# pass index value 3 to access third column
print(dataframe1[3])
Output
Name
1 Juan
2 Alcaraz
3 Simantha
Vote
1 TRUE
2 FALSE
3 TRUE
In the above example, we have created a dataframe named dataframe1 with three columns Name
, Age
, Vote
.
Here,
dataframe[1]
- accesses all the elements of 1st column i.e.Name
dataframe[2]
- accesses all the elements of 3rd column i.e.Vote
Example 2: Use Column Name to Access Dataframe Column in R
# Create a data frame
dataframe1 <- data.frame (
Name = c("Juan", "Alcaraz", "Simantha"),
Age = c(22, 15, 19),
Vote = c(TRUE, FALSE, TRUE)
)
# access Name column
print(dataframe1[["Name"]])
# access Age column
print(dataframe1[["Age"]])
Output
[1] "Juan" "Alcaraz" "Simantha"
[1] 22 15 19
In the above example, we have used the [[ ]]
operator to access columns of the dataframe named dataframe1.
Here,
dataframe[["Name"]]
- accesses all the elements of theName
column.dataframe[["Age"]]
- accesses all the elements of theAge
column.
Example 3: Use Column Name and $ to Access Column
# Create a data frame
dataframe1 <- data.frame (
Name = c("Juan", "Alcaraz", "Simantha"),
Age = c(22, 15, 19),
Vote = c(TRUE, FALSE, TRUE)
)
# access Age column
print(dataframe1$Age)
# access Vote column
print(dataframe1$Vote)
Output
[1] 22 15 19
[1] TRUE FALSE TRUE
In the above example, we have used the $
operator and column name to access columns of the dataframe1 dataframe.
Here,
dataframe$Age
- accesses all the elements of theAge
column.dataframe$Vote
- accesses all the elements of theVote
column.