# How to Use Dollar Sign (\$) Operator in R

You can use the dollar sign operator (\$) in R to create and access variables in lists and data frames.

The following examples shows four common way to use this operator in practice.

### Example 1: Use Dollar Sign to Create Variable in List

Suppose we create the following list in R:

```#create list
my_list <- list(A= c('X', 'Y', 'Z'),
B=20,
C=1:5)

#view list
my_list

\$A
 "X" "Y" "Z"

\$B
 20

\$C
 1 2 3 4 5```

We can use the dollar sign operator (\$) to create a new variable in this list:

```#create new variable in list
my_list\$D <- c('Hey', 'Hi', 'Hello')

#view updated list
my_list

\$A
 "X" "Y" "Z"

\$B
 20

\$C
 1 2 3 4 5

\$D
 "Hey"   "Hi"    "Hello"
```

Notice that the new variable D has been added to the list.

### Example 2: Use Dollar Sign to Access Variable in List

We can also use the dollar sign operator (\$) to access a specific variable in a list.

For example, we can use the following code to access the variable C in the list:

```#create list
my_list <- list(A= c('X', 'Y', 'Z'),
B=20,
C=1:5)

#access variable C
my_list\$C

 1 2 3 4 5```

Notice that only the values for variable C are returned.

### Example 3: Use Dollar Sign to Create Variable in Data Frame

Suppose we create the following data frame in R:

```#create data frame
df <- data.frame(team=c('Mavs', 'Spurs', 'Rockets', 'Nets'),
points=c(140, 115, 109, 98))

#view data frame
df

team points
1    Mavs    140
2   Spurs    115
3 Rockets    109
4    Nets     98
```

We can use the dollar sign operator (\$) to create a new variable in the data frame called assists:

```#create new variable called assists
df\$assists <- c(20, 25, 29, 49)

#view updated data frame
df

team points assists
1    Mavs    140      20
2   Spurs    115      25
3 Rockets    109      29
4    Nets     98      49```

Notice that the new variable assists has been added to the data frame.

### Example 4: Use Dollar Sign to Access Variable in Data Frame

We can also use the dollar sign operator (\$) to access a specific variable in a data frame.

For example, we can use the following code to access the points variable in the data frame:

```#create data frame
df <- data.frame(team=c('Mavs', 'Spurs', 'Rockets', 'Nets'),
points=c(140, 115, 109, 98))

#access values for points
df\$points

 140 115 109  98
```

Notice that only the values for the points variable are returned.