Accessing elements in R with [], [[]], and $
📖 Scenario: You are working with a list in R that stores information about a book. You want to learn how to access different parts of this list using three common methods: [], [[]], and $.
🎯 Goal: Build a simple R script that creates a list with book details, sets a variable for the key to access, extracts information using the three methods, and prints the results.
📋 What You'll Learn
Create a list named
book with exact elements: title = "The Hobbit", author = "J.R.R. Tolkien", year = 1937Create a variable named
key and set it to "author"Use
book["title"] to access the title and store it in title_bracketsUse
book[[key]] to access the author and store it in author_double_bracketsUse
book$year to access the year and store it in year_dollarPrint the three variables in order:
title_brackets, author_double_brackets, year_dollar💡 Why This Matters
🌍 Real World
Lists in R are used to store related data like records, settings, or grouped information. Knowing how to access elements helps you work with data efficiently.
💼 Career
Data analysts and scientists often manipulate lists in R to extract and analyze data. Understanding these access methods is essential for data cleaning and preparation.
Progress0 / 4 steps