How to use the dollar sign ($) in R

How to use the dollar sign in R, You’ll learn how to use the $ operator in the R programming language in this tutorial.

Example 1: How to use the dollar sign in R

In R, the $ operator is typically used to extract or subset a specified part of a data item.

This could be a data frame object or a list, for example.

Will show you how to use the $ operator to extract values from the data frame columns in the below example.

To get started with the example, we’ll need to establish a data frame in R.

We can do that by running the following R code.

data <- data.frame(A = 5:10,  B= 150:155,  C =12:17)
   A   B  C
1  5 150 12
2  6 151 13
3  7 152 14
4  8 153 15
5  9 154 16
6 10 155 17

With the prior R syntax, we built a data frame with five rows and three columns A, B, and C are the names of our variables.

Let’s say we wish to extract the variable C from the third column of our data frame. Then, as seen below, we may utilise the $ operator.


[1] 12 13 14 15 16 17

Take a look at the previous RStudio console output. As you can see, we’ve merely taken the numbers from the variable x2.

Example 2: Accessing a List Element with the $ Operator

The $ operator can also be used to return individual list elements, as previously indicated. To demonstrate this, we’ll first make an example list in R:

List <- list(X = 1:5,      
Y = letters[2:6],
Z = 10:15)
[1] 1 2 3 4 5

[1] "b" "c" "d" "e" "f"

[1] 10 11 12 13 14 15

The structure of our list may be seen in the previous RStudio console output. A, B, and C are the three list items that make up our list. The values in each of these list components are different.

Let’s pretend we simply want to get the values of the list element B. We can utilize the $ operator in this scenario, as seen below:

[1] 1 2 3 4 5

Only the values contained in the second list element X are shown in the previous RStudio console output.

Subscribe to our newsletter!

[newsletter_form type=”minimal”]

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

10 − 6 =