What is the = operator for?

Hi everyone!

I am very new to R and am confused about the meaning of the = operator.

In this thread, the user andresrcs wrote the following code:

# Provided sample data
df <- structure(list(Country = c("Algeria", "Angola", "Benin", "Botswana",
                           "Burkina Faso", "Burundi", "Cameroon", "Cape Verde", "Central African Republic",
                           "Chad"), Authorship = c(273, 1, 34, 70, 35, 7, 88, 11, 0, 6),
               UnAuthorship = c(49, 16, 29, 75, 18, 2, 31, 1, 4, 35), PA = c(84.7826087,
                                                                             5.882352941, 53.96825397, 48.27586207, 66.03773585, 77.77777778,
                                                                             73.94957983, 91.66666667, 0, 14.63414634), PUA = c(15.2173913,
                                                                                                                                94.11764706, 46.03174603, 51.72413793, 33.96226415, 22.22222222,
                                                                                                                                26.05042017, 8.333333333, 100, 85.36585366)), row.names = c(NA,
                                                                                                                                                                                            -10L), class = c("tbl_df", "tbl", "data.frame"))

# Relevant code
library(tidyverse)

df %>% 
    pivot_longer(c("PA", "PUA"), names_to = "type") %>% 
    ggplot(aes(y = Country, x = value, fill = type)) +
    geom_col() +
    scale_x_continuous(labels = scales::percent_format(scale = 1))

Created on 2021-12-05 by the reprex package (v2.0.1)

My understanding is that andresrcs is creating a list in the structure() function, and is adding items, like "Country", to the list. They add vectors to these list items. However, I do not understand why andresrcs assigns values to the list items using = instead of <-.I thought that <- was the main assignment operator. Do we use <- to assign values to variables and = to assign values to function arguments?

There are differences I do not understand between <- and = but the following seems to cover everything I have had to do in R. Always use = to assign function arguments. Use either <- or = to assign to variables.
For variables, <- seems to be more popular in my experience.

From: assignOps function - RDocumentation

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.