10.3 Refer/Create Specific Variable

We can reference a particular variable (column) in the data frame with the following notation: dataframe_name$variable_name. The $ sign is a separator to distinguish the name of the data frame and the variable name.

Typing mean(dat$t) indicates the average of \(t\).

mean(dat$t)

You can use the same syntax to create a new variable and add it directly to the data frame. The key is that the length of the variable needs to be the same length as the data frame itself.

For example, the following code successfully adds ObsNum to the data frame:

dat$ObsNum <- 1:nrow(dat)

You can see in the Environment Window that the number of variables has increased by one and you can view the edited data frame by typing dat.

The following code produces an error when trying to add oops to the data frame:

dat$oops <- 1:2