Columns Accessors
Since data frames have names on their columns, you should be able to extract necessary data using them.
There are several ways in R to refer to a particular column using naming. One of them is the same as in vectors and matrices: column name within square brackets (for example, data[, "col_name"]). The second way is unique for data frames - using the dollar $ sign. The syntax is data$col_name (yes, without quotation marks). For example, you can extract the column "Age" from the data frame created in the last chapter.
12345678910# Data name <- c("Alex", "Julia", "Finn") age <- c(24, 43, 32) gender <- c("M", "F", "M") # Creating a data frame test <- data.frame(name, age, gender) # Extracting the name column using two ways test[,"name"] test$name
Swipe to start coding
Let's work with the mtcars dataset. Your tasks are:
- Extract the
cylcolumn values using square brackets. - Extract the
dispcolumn values using the dollar$sign.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain the difference between using square brackets and the dollar sign for extracting columns?
What happens if I try to extract a column that doesn't exist?
Can I use these methods to extract multiple columns at once?
Awesome!
Completion rate improved to 5.56
Columns Accessors
Swipe to show menu
Since data frames have names on their columns, you should be able to extract necessary data using them.
There are several ways in R to refer to a particular column using naming. One of them is the same as in vectors and matrices: column name within square brackets (for example, data[, "col_name"]). The second way is unique for data frames - using the dollar $ sign. The syntax is data$col_name (yes, without quotation marks). For example, you can extract the column "Age" from the data frame created in the last chapter.
12345678910# Data name <- c("Alex", "Julia", "Finn") age <- c(24, 43, 32) gender <- c("M", "F", "M") # Creating a data frame test <- data.frame(name, age, gender) # Extracting the name column using two ways test[,"name"] test$name
Swipe to start coding
Let's work with the mtcars dataset. Your tasks are:
- Extract the
cylcolumn values using square brackets. - Extract the
dispcolumn values using the dollar$sign.
Solution
Thanks for your feedback!
single