error target of assignment expands to non language object

Join Our ggplot2 Data Visualization Course Starting on November 25 (Click for More Info)

Joachim Schork Image Course

R Error: target of assignment expands to non-language object (Example)

In this article, you’ll learn how to handle the Error in X : target of assignment expands to non-language object in the R programming language .

The content is structured as follows:

If you want to learn more about these contents, keep reading!

Example 1: Reproduce the Error in X : target of assignment expands to non-language object

The following R syntax explains how to replicate the Error in X : target of assignment expands to non-language object.

Let’s assume that we want to assign the values 1 to 5 to a new data object. Then, we might try top use the following R code:

Unfortunately, the Error in X : target of assignment expands to non-language object was returned after executing the previous R syntax.

The reason for this is that we have tried to assign our values to a vector of values itself. However, we should assign our values to the name of a regular data object.

In the next example, I#ll explain how to resolve this problem!

Example 2: Fix the Error in X : target of assignment expands to non-language object

In Example 2, I’ll explain how to handle the Error in X : target of assignment expands to non-language object.

For this, we need to specify a valid data object name on the left side of our assignment arrow .

Have a look at the following R code:

Works fine!

Video, Further Resources & Summary

I have recently published a video instruction on my YouTube channel, which shows the contents of this page. You can find the video below.

The YouTube video will be added soon.

Also, you may want to have a look at the related articles on https://statisticsglobe.com/.

  • Handling Warning & Error Messages in R
  • All R Programming Tutorials

In summary: In this tutorial, I have shown how to deal with the Error in X : target of assignment expands to non-language object in the R programming language. Don’t hesitate to tell me about it in the comments section below, in case you have any additional questions.

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy .

Leave a Reply Cancel reply

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

Attachment The maximum upload file size: 2 MB. You can upload: image . Drop file here

Post Comment

Joachim Schork Statistician Programmer

I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.

Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy .

error target of assignment expands to non language object

Related Tutorials

R Error: plot.new has not been called yet (2 Examples)

R Error: plot.new has not been called yet (2 Examples)

R Warning Message in as.POSIXct.POSIXlt(x) : unknown timezone

R Warning Message in as.POSIXct.POSIXlt(x) : unknown timezone

target of assignment expands to non-language object ERROR message

I am trying to assign model results to an object in a programmatic way so that I would only need to change the model run number to view particular model run results. However I am getting error message of "target of assignment expands to non-language object"

I found a solution using the assign function. However, I have to add in eval(parse(text = ...) to the function for it to execute. Is there a way to streamline in the beginning code to include this eval(parse(text = ...) ?

perhaps it would be more convenient to save the different model results into a list, and then index into the list for any particular result.

Thank you! the models were evaluated in different software but the outputs are used in R to explore. I will placing model results in list and then index to explore.

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

data hacks r programming logo website

Error in R – target of assignment expands to non-language object (2 Examples)

In this tutorial you’ll learn how to avoid the Error in X : target of assignment expands to non-language object in the R programming language .

Example 1: Replicate the Error in X – target of assignment expands to non-language object

1:3 <- 10 # Try to assign value # Error in 1:3 <- 10 : target of assignment expands to non-language object

Example 2: Fix the Error in X : target of assignment expands to non-language object

my_data <- 10 # Correct way to assign value my_data # Display new data object # [1] 10

Further Resources

Have a look at the following tutorials. They illustrate topics such as ggplot2, data objects, lists, and coding errors.

  • ggplot2 Error in R – Don’t know how to automatically pick scale for object of type function
  • How to Fix the Error – Coerce List Object to Type Double
  • Error in R – Object of Type Closure is not Subsettable

Leave a Reply Cancel reply

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

Post Comment

How to Apply the drop() Function in R (Example Code)

How to apply the addmargins() function in r (example code), r save results of loop in data frame (example code).

ProgrammingR

Beginner to advanced resources for the R programming language

  • Search for:

How to Solve the R Error: attempt to apply non-function

This error message really needs to be renamed: check for the clumsy typo . When you see this, walk through your formulas around the location of the error message. Ninety nine percent of the time you’re looking at a basic syntax issue with how you are laying out your calculations in your r code. This is a common error when you have a clumsy typo in an argument or mathematical operator.

One of your calculations, likely one which uses brackets to break up your order of operations, is missing an operator somewhere in the code. There is a significant difference in how R handles the following two statements, identical except for a single character.

  • profit = units * (unit_price – unit_cost)
  • profit = units (unit_price – unit_cost)

In the first example, R will solve for the calculation inside the brackets (price – cost) and multiply it by the value in the variable units. Simple math. Unfortunately, this is a massive change in the mathematical operation.

In the second example, since there is no * to identify what operation to pursue, R interprets the whole thing as a function call. Solve for the difference between price and cost and apply the function that is named units to transform the result.

Except of course, there is no function named units. But there is an object named units. So what the heck, lets apply THAT to the value in question. So a very confused variable (units) which is most definitely NOT an R function (not even close!) is suddenly “applied” (Dr. Evil air quotes) to the value we fed it.

At which point the program realizes it is trying to do completely unnatural things to an innocent little variable and throws an error: attempt to apply non-function.

SIGH. And this is why we can’t have nice things.

How To Fix “Attempt to apply non-function”

Joking aside, this one is straight forward. Look at your calculations with a fine toothed comb, paying close attention to any situation where you use brackets. Make sure you separate those bracketed items from other elements of the calculation with an appropriate operator (+, -, %, *, other operators ).

If all else fails, check your function name and object method references. This is especially true if you imported an r package that overlaps with your existing r code function(s).

Troubleshooting Tips :

  • Carefully examine your code for any missing operators, like  + ,  - ,  * , or  % .
  • Use appropriate brackets to ensure the correct order of operations.
  • Confirm that your function calls and object references are accurate, particularly after integrating new packages that might contain overlapping function names with your existing code.

By diligently reviewing your code for these small but impactful oversights, you can avoid one of the most common errors in R programming. Remember, even a single-character typo can significantly shift the intended meaning of your code, causing R to stumble and produce an error. So, maintaining a keen eye for detail is crucial in resolving the “attempt to apply non-function” message and keeping your coding efforts on track.

Frequently Asked Questions

Resolving the ‘error in x self finalize()’ in r.

To correct the issue where R is indicating a non-function is being called, review the function’s syntax and ensure that all objects are correctly defined and being used appropriately. Debugging may reveal a variable is being called as a function erroneously.

Addressing the ‘Computation failed in stat_bin’ Error in ggplot2

When encountering this error message with ggplot2, check for syntax errors in the code, such as missing or misplaced operators. Make sure that the ggplot2 library is correctly installed and loaded. Additionally, verify that all variables are correctly formatted for the statistical computation.

Corrective Steps for ‘Read_csv: attempt to apply non-function’ Error in R

If this error occurs while trying to read a CSV file in R, ensure that the reader function is correctly called with the appropriate syntax. The package containing the reader function (e.g., readr) must be installed and loaded.

Diagnosing the ‘Invalid Call to Non-Function’ Alert in Google Sheets

An alert such as this in Google Sheets typically arises from a formula error. Inspect the formula for correctness and consistency, paying close attention to the syntax and reference calls made within the formula.

Handling ‘Target of Assignment Expands to Non-Language Object’ in R

When R presents this message, it often signifies a  syntactical mistake  with the assignment operator. Double-check that the left-hand side of an assignment is a valid language object in R, such as a variable name, and is not inadvertently a function call or other structure.

Deciphering and Fixing ‘Could Not Find Function’ in R

The message ‘ Could not find function ‘ suggests that R cannot locate a specific function within the available packages or the global environment. To resolve this, confirm that the  appropriate package is installed  and loaded. If it is a user-defined function, check that it is correctly written and accessible in the script.

R needs to chill on this error message. This is basically a syntax error — a bad parenthesis or creating a conflict through the juxtaposition of an argument or expression.

R error target of assignment expands to non-language object

ERROR R Source (Table) 3:1 Execute failed: Error in R code: Error: target of assignment expands to non-language object

In the event you get this error message, just change the name of the file you are trying to read with readxl.

My scenario had files named 2020-ref… and by changing the name of the file to remove the hyphen and also move the numbers to the end of the file name, I was able to resolve the error.

If you search for this on other sites, the rabbit hole is endless. I compared the code to another workflow where I used the feature and found the only difference to be the file names. In all successful nodes the file names start with a string, non numeric character, and no -'s.

Hope this helps.

:+1:

6 Functions

6.1 introduction.

If you’re reading this book, you’ve probably already created many R functions and know how to use them to reduce duplication in your code. In this chapter, you’ll learn how to turn that informal, working knowledge into more rigorous, theoretical understanding. And while you’ll see some interesting tricks and techniques along the way, keep in mind that what you’ll learn here will be important for understanding the more advanced topics discussed later in the book.

Answer the following questions to see if you can safely skip this chapter. You can find the answers in Section 6.9 .

What are the three components of a function?

What does the following code return?

How would you usually write this code?

How could you make this call easier to read?

Does the following code throw an error when executed? Why or why not?

What is an infix function? How do you write it? What’s a replacement function? How do you write it?

How do you ensure that cleanup action occurs regardless of how a function exits?

Section 6.2 describes the basics of creating a function, the three main components of a function, and the exception to many function rules: primitive functions (which are implemented in C, not R).

Section 6.3 discusses the strengths and weaknesses of the three forms of function composition commonly used in R code.

Section 6.4 shows you how R finds the value associated with a given name, i.e. the rules of lexical scoping.

Section 6.5 is devoted to an important property of function arguments: they are only evaluated when used for the first time.

Section 6.6 discusses the special ... argument, which allows you to pass on extra arguments to another function.

Section 6.7 discusses the two primary ways that a function can exit, and how to define an exit handler, code that is run on exit, regardless of what triggers it.

Section 6.8 shows you the various ways in which R disguises ordinary function calls, and how you can use the standard prefix form to better understand what’s going on.

6.2 Function fundamentals

To understand functions in R you need to internalise two important ideas:

  • Functions can be broken down into three components: arguments, body, and environment.

There are exceptions to every rule, and in this case, there is a small selection of “primitive” base functions that are implemented purely in C.

  • Functions are objects, just as vectors are objects.

6.2.1 Function components

A function has three parts:

The formals() , the list of arguments that control how you call the function.

The body() , the code inside the function.

The environment() , the data structure that determines how the function finds the values associated with the names.

While the formals and body are specified explicitly when you create a function, the environment is specified implicitly, based on where you defined the function. The function environment always exists, but it is only printed when the function isn’t defined in the global environment.

I’ll draw functions as in the following diagram. The black dot on the left is the environment. The two blocks to the right are the function arguments. I won’t draw the body, because it’s usually large, and doesn’t help you understand the shape of the function.

error target of assignment expands to non language object

Like all objects in R, functions can also possess any number of additional attributes() . One attribute used by base R is srcref , short for source reference. It points to the source code used to create the function. The srcref is used for printing because, unlike body() , it contains code comments and other formatting.

6.2.2 Primitive functions

There is one exception to the rule that a function has three components. Primitive functions, like sum() and [ , call C code directly.

They have either type builtin or type special .

These functions exist primarily in C, not R, so their formals() , body() , and environment() are all NULL :

Primitive functions are only found in the base package. While they have certain performance advantages, this benefit comes at a price: they are harder to write. For this reason, R-core generally avoids creating them unless there is no other option.

6.2.3 First-class functions

It’s very important to understand that R functions are objects in their own right, a language property often called “first-class functions”. Unlike in many other languages, there is no special syntax for defining and naming a function: you simply create a function object (with function ) and bind it to a name with <- :

error target of assignment expands to non language object

While you almost always create a function and then bind it to a name, the binding step is not compulsory. If you choose not to give a function a name, you get an anonymous function . This is useful when it’s not worth the effort to figure out a name:

A final option is to put functions in a list:

In R, you’ll often see functions called closures . This name reflects the fact that R functions capture, or enclose, their environments, which you’ll learn more about in Section 7.4.2 .

6.2.4 Invoking a function

You normally call a function by placing its arguments, wrapped in parentheses, after its name: mean(1:10, na.rm = TRUE) . But what happens if you have the arguments already in a data structure?

You can instead use do.call() : it has two arguments. The function to call, and a list containing the function arguments:

We’ll come back to this idea in Section 19.6 .

6.2.5 Exercises

Given a name, like "mean" , match.fun() lets you find a function. Given a function, can you find its name? Why doesn’t that make sense in R?

It’s possible (although typically not useful) to call an anonymous function. Which of the two approaches below is correct? Why?

A good rule of thumb is that an anonymous function should fit on one line and shouldn’t need to use {} . Review your code. Where could you have used an anonymous function instead of a named function? Where should you have used a named function instead of an anonymous function?

What function allows you to tell if an object is a function? What function allows you to tell if a function is a primitive function?

This code makes a list of all functions in the base package.

Use it to answer the following questions:

Which base function has the most arguments?

How many base functions have no arguments? What’s special about those functions?

How could you adapt the code to find all primitive functions?

What are the three important components of a function?

When does printing a function not show the environment it was created in?

6.3 Function composition

Base R provides two ways to compose multiple function calls. For example, imagine you want to compute the population standard deviation using sqrt() and mean() as building blocks:

You either nest the function calls:

Or you save the intermediate results as variables:

The magrittr package 35 provides a third option: the binary operator %>% , which is called the pipe and is pronounced as “and then”.

x %>% f() is equivalent to f(x) ; x %>% f(y) is equivalent to f(x, y) . The pipe allows you to focus on the high-level composition of functions rather than the low-level flow of data; the focus is on what’s being done (the verbs), rather than on what’s being modified (the nouns). This style is common in Haskell and F#, the main inspiration for magrittr, and is the default style in stack based programming languages like Forth and Factor.

Each of the three options has its own strengths and weaknesses:

Nesting, f(g(x)) , is concise, and well suited for short sequences. But longer sequences are hard to read because they are read inside out and right to left. As a result, arguments can get spread out over long distances creating the Dagwood sandwich problem.

Intermediate objects, y <- f(x); g(y) , requires you to name intermediate objects. This is a strength when objects are important, but a weakness when values are truly intermediate.

Piping, x %>% f() %>% g() , allows you to read code in straightforward left-to-right fashion and doesn’t require you to name intermediate objects. But you can only use it with linear sequences of transformations of a single object. It also requires an additional third party package and assumes that the reader understands piping.

Most code will use a combination of all three styles. Piping is more common in data analysis code, as much of an analysis consists of a sequence of transformations of an object (like a data frame or plot). I tend to use piping infrequently in packages; not because it is a bad idea, but because it’s often a less natural fit.

6.4 Lexical scoping

In Chapter 2 , we discussed assignment, the act of binding a name to a value. Here we’ll discuss scoping , the act of finding the value associated with a name.

The basic rules of scoping are quite intuitive, and you’ve probably already internalised them, even if you never explicitly studied them. For example, what will the following code return, 10 or 20? 36

In this section, you’ll learn the formal rules of scoping as well as some of its more subtle details. A deeper understanding of scoping will help you to use more advanced functional programming tools, and eventually, even to write tools that translate R code into other languages.

R uses lexical scoping 37 : it looks up the values of names based on how a function is defined, not how it is called. “Lexical” here is not the English adjective that means relating to words or a vocabulary. It’s a technical CS term that tells us that the scoping rules use a parse-time, rather than a run-time structure.

R’s lexical scoping follows four primary rules:

  • Name masking
  • Functions versus variables
  • A fresh start
  • Dynamic lookup

6.4.1 Name masking

The basic principle of lexical scoping is that names defined inside a function mask names defined outside a function. This is illustrated in the following example.

If a name isn’t defined inside a function, R looks one level up.

The same rules apply if a function is defined inside another function. First, R looks inside the current function. Then, it looks where that function was defined (and so on, all the way up to the global environment). Finally, it looks in other loaded packages.

Run the following code in your head, then confirm the result by running the code. 38

The same rules also apply to functions created by other functions, which I call manufactured functions, the topic of Chapter 10 .

6.4.2 Functions versus variables

In R, functions are ordinary objects. This means the scoping rules described above also apply to functions:

However, when a function and a non-function share the same name (they must, of course, reside in different environments), applying these rules gets a little more complicated. When you use a name in a function call, R ignores non-function objects when looking for that value. For example, in the code below, g09 takes on two different values:

For the record, using the same name for different things is confusing and best avoided!

6.4.3 A fresh start

What happens to values between invocations of a function? Consider the example below. What will happen the first time you run this function? What will happen the second time? 39 (If you haven’t seen exists() before, it returns TRUE if there’s a variable with that name and returns FALSE if not.)

You might be surprised that g11() always returns the same value. This happens because every time a function is called a new environment is created to host its execution. This means that a function has no way to tell what happened the last time it was run; each invocation is completely independent. We’ll see some ways to get around this in Section 10.2.4 .

6.4.4 Dynamic lookup

Lexical scoping determines where, but not when to look for values. R looks for values when the function is run, not when the function is created. Together, these two properties tell us that the output of a function can differ depending on the objects outside the function’s environment:

This behaviour can be quite annoying. If you make a spelling mistake in your code, you won’t get an error message when you create the function. And depending on the variables defined in the global environment, you might not even get an error message when you run the function.

To detect this problem, use codetools::findGlobals() . This function lists all the external dependencies (unbound symbols) within a function:

To solve this problem, you can manually change the function’s environment to the emptyenv() , an environment which contains nothing:

The problem and its solution reveal why this seemingly undesirable behaviour exists: R relies on lexical scoping to find everything , from the obvious, like mean() , to the less obvious, like + or even { . This gives R’s scoping rules a rather beautiful simplicity.

6.4.5 Exercises

What does the following code return? Why? Describe how each of the three c ’s is interpreted.

What are the four principles that govern how R looks for values?

What does the following function return? Make a prediction before running the code yourself.

6.5 Lazy evaluation

In R, function arguments are lazily evaluated : they’re only evaluated if accessed. For example, this code doesn’t generate an error because x is never used:

This is an important feature because it allows you to do things like include potentially expensive computations in function arguments that will only be evaluated if needed.

6.5.1 Promises

Lazy evaluation is powered by a data structure called a promise , or (less commonly) a thunk. It’s one of the features that makes R such an interesting programming language (we’ll return to promises again in Section 20.3 ).

A promise has three components:

An expression, like x + y , which gives rise to the delayed computation.

An environment where the expression should be evaluated, i.e. the environment where the function is called. This makes sure that the following function returns 11, not 101:

This also means that when you do assignment inside a call to a function, the variable is bound outside of the function, not inside of it.

A value, which is computed and cached the first time a promise is accessed when the expression is evaluated in the specified environment. This ensures that the promise is evaluated at most once, and is why you only see “Calculating…” printed once in the following example.

You cannot manipulate promises with R code. Promises are like a quantum state: any attempt to inspect them with R code will force an immediate evaluation, making the promise disappear. Later, in Section 20.3 , you’ll learn about quosures, which convert promises into an R object where you can easily inspect the expression and the environment.

6.5.2 Default arguments

Thanks to lazy evaluation, default values can be defined in terms of other arguments, or even in terms of variables defined later in the function:

Many base R functions use this technique, but I don’t recommend it. It makes the code harder to understand: to predict what will be returned, you need to know the exact order in which default arguments are evaluated.

The evaluation environment is slightly different for default and user supplied arguments, as default arguments are evaluated inside the function. This means that seemingly identical calls can yield different results. It’s easiest to see this with an extreme example:

6.5.3 Missing arguments

To determine if an argument’s value comes from the user or from a default, you can use missing() :

missing() is best used sparingly, however. Take sample() , for example. How many arguments are required?

It looks like both x and size are required, but if size is not supplied, sample() uses missing() to provide a default. If I were to rewrite sample, I’d use an explicit NULL to indicate that size is not required but can be supplied:

With the binary pattern created by the %||% infix function, which uses the left side if it’s not NULL and the right side otherwise, we can further simplify sample() :

Because of lazy evaluation, you don’t need to worry about unnecessary computation: the right side of %||% will only be evaluated if the left side is NULL .

6.5.4 Exercises

What important property of && makes x_ok() work?

What is different with this code? Why is this behaviour undesirable here?

What does this function return? Why? Which principle does it illustrate?

In hist() , the default value of xlim is range(breaks) , the default value for breaks is "Sturges" , and

Explain how hist() works to get a correct xlim value.

Explain why this function works. Why is it confusing?

How many arguments are required when calling library() ?

6.6 ... (dot-dot-dot)

Functions can have a special argument ... (pronounced dot-dot-dot). With it, a function can take any number of additional arguments. In other programming languages, this type of argument is often called varargs (short for variable arguments), and a function that uses it is said to be variadic.

You can also use ... to pass those additional arguments on to another function.

Using a special form, ..N , it’s possible (but rarely useful) to refer to elements of ... by position:

More useful is list(...) , which evaluates the arguments and stores them in a list:

(See also rlang::list2() to support splicing and to silently ignore trailing commas, and rlang::enquos() to capture unevaluated arguments, the topic of quasiquotation .)

There are two primary uses of ... , both of which we’ll come back to later in the book:

If your function takes a function as an argument, you want some way to pass additional arguments to that function. In this example, lapply() uses ... to pass na.rm on to mean() :

We’ll come back to this technique in Section 9.2.3 .

If your function is an S3 generic, you need some way to allow methods to take arbitrary extra arguments. For example, take the print() function. Because there are different options for printing depending on the type of object, there’s no way to pre-specify every possible argument and ... allows individual methods to have different arguments:

We’ll come back to this use of ... in Section 13.4.3 .

Using ... comes with two downsides:

When you use it to pass arguments to another function, you have to carefully explain to the user where those arguments go. This makes it hard to understand what you can do with functions like lapply() and plot() .

A misspelled argument will not raise an error. This makes it easy for typos to go unnoticed:

6.6.1 Exercises

Explain the following results:

Explain how to find the documentation for the named arguments in the following function call:

error target of assignment expands to non language object

Why does plot(1:10, col = "red") only colour the points, not the axes or labels? Read the source code of plot.default() to find out.

6.7 Exiting a function

Most functions exit in one of two ways 40 : they either return a value, indicating success, or they throw an error, indicating failure. This section describes return values (implicit versus explicit; visible versus invisible), briefly discusses errors, and introduces exit handlers, which allow you to run code when a function exits.

6.7.1 Implicit versus explicit returns

There are two ways that a function can return a value:

Implicitly, where the last evaluated expression is the return value:

Explicitly, by calling return() :

6.7.2 Invisible values

Most functions return visibly: calling the function in an interactive context prints the result.

However, you can prevent automatic printing by applying invisible() to the last value:

To verify that this value does indeed exist, you can explicitly print it or wrap it in parentheses:

Alternatively, you can use withVisible() to return the value and a visibility flag:

The most common function that returns invisibly is <- :

This is what makes it possible to chain assignments:

In general, any function called primarily for a side effect (like <- , print() , or plot() ) should return an invisible value (typically the value of the first argument).

6.7.3 Errors

If a function cannot complete its assigned task, it should throw an error with stop() , which immediately terminates the execution of the function.

An error indicates that something has gone wrong, and forces the user to deal with the problem. Some languages (like C, Go, and Rust) rely on special return values to indicate problems, but in R you should always throw an error. You’ll learn more about errors, and how to handle them, in Chapter 8 .

6.7.4 Exit handlers

Sometimes a function needs to make temporary changes to the global state. But having to cleanup those changes can be painful (what happens if there’s an error?). To ensure that these changes are undone and that the global state is restored no matter how a function exits, use on.exit() to set up an exit handler . The following simple example shows that the exit handler is run regardless of whether the function exits normally or with an error.

Always set add = TRUE when using on.exit() . If you don’t, each call to on.exit() will overwrite the previous exit handler. Even when only registering a single handler, it’s good practice to set add = TRUE so that you won’t get any unpleasant surprises if you later add more exit handlers.

on.exit() is useful because it allows you to place clean-up code directly next to the code that requires clean-up:

Coupled with lazy evaluation, this creates a very useful pattern for running a block of code in an altered environment:

The use of force() isn’t strictly necessary here as simply referring to code will force its evaluation. However, using force() makes it very clear that we are deliberately forcing the execution. You’ll learn other uses of force() in Chapter 10 .

The withr package 41 provides a collection of other functions for setting up a temporary state.

In R 3.4 and earlier, on.exit() expressions are always run in order of creation:

This can make cleanup a little tricky if some actions need to happen in a specific order; typically you want the most recent added expression to be run first. In R 3.5 and later, you can control this by setting after = FALSE :

6.7.5 Exercises

What does load() return? Why don’t you normally see these values?

What does write.table() return? What would be more useful?

How does the chdir parameter of source() compare to with_dir() ? Why might you prefer one to the other?

Write a function that opens a graphics device, runs the supplied code, and closes the graphics device (always, regardless of whether or not the plotting code works).

We can use on.exit() to implement a simple version of capture.output() .

Compare capture.output() to capture.output2() . How do the functions differ? What features have I removed to make the key ideas easier to see? How have I rewritten the key ideas so they’re easier to understand?

6.8 Function forms

To understand computations in R, two slogans are helpful: Everything that exists is an object. Everything that happens is a function call. — John Chambers

While everything that happens in R is a result of a function call, not all calls look the same. Function calls come in four varieties:

prefix : the function name comes before its arguments, like foofy(a, b, c) . These constitute of the majority of function calls in R.

infix : the function name comes in between its arguments, like x + y . Infix forms are used for many mathematical operators, and for user-defined functions that begin and end with % .

replacement : functions that replace values by assignment, like names(df) <- c("a", "b", "c") . They actually look like prefix functions.

special : functions like [[ , if , and for . While they don’t have a consistent structure, they play important roles in R’s syntax.

While there are four forms, you actually only need one because any call can be written in prefix form. I’ll demonstrate this property, and then you’ll learn about each of the forms in turn.

6.8.1 Rewriting to prefix form

An interesting property of R is that every infix, replacement, or special form can be rewritten in prefix form. Doing so is useful because it helps you better understand the structure of the language, it gives you the real name of every function, and it allows you to modify those functions for fun and profit.

The following example shows three pairs of equivalent calls, rewriting an infix form, replacement form, and a special form into prefix form.

Suprisingly, in R, for can be called like a regular function! The same is true for basically every operation in R, which means that knowing the function name of a non-prefix function allows you to override its behaviour. For example, if you’re ever feeling particularly evil, run the following code while a friend is away from their computer. It will introduce a fun bug: 10% of the time, it will add 1 to any numeric calculation inside the parentheses.

Of course, overriding built-in functions like this is a bad idea, but, as you’ll learn in Section 21.2.5 , it’s possible to apply it only to selected code blocks. This provides a clean and elegant approach to writing domain specific languages and translators to other languages.

A more useful application comes up when using functional programming tools. For example, you could use lapply() to add 3 to every element of a list by first defining a function add() :

But we can also get the same result simply by relying on the existing + function:

We’ll explore this idea in detail in Section 9 .

6.8.2 Prefix form

The prefix form is the most common form in R code, and indeed in the majority of programming languages. Prefix calls in R are a little special because you can specify arguments in three ways:

  • By position, like help(mean) .
  • Using partial matching, like help(top = mean) .
  • By name, like help(topic = mean) .

As illustrated by the following chunk, arguments are matched by exact name, then with unique prefixes, and finally by position.

In general, use positional matching only for the first one or two arguments; they will be the most commonly used, and most readers will know what they are. Avoid using positional matching for less commonly used arguments, and never use partial matching. Unfortunately you can’t disable partial matching, but you can turn it into a warning with the warnPartialMatchArgs option:

6.8.3 Infix functions

Infix functions get their name from the fact the function name comes inbetween its arguments, and hence have two arguments. R comes with a number of built-in infix operators: : , :: , ::: , $ , @ , ^ , * , / , + , - , > , >= , < , <= , == , != , ! , & , && , | , || , ~ , <- , and <<- . You can also create your own infix functions that start and end with % . Base R uses this pattern to define %% , %*% , %/% , %in% , %o% , and %x% .

Defining your own infix function is simple. You create a two argument function and bind it to a name that starts and ends with % :

The names of infix functions are more flexible than regular R functions: they can contain any sequence of characters except for % . You will need to escape any special characters in the string used to define the function, but not when you call it:

R’s default precedence rules mean that infix operators are composed left to right:

There are two special infix functions that can be called with a single argument: + and - .

6.8.4 Replacement functions

Replacement functions act like they modify their arguments in place, and have the special name xxx<- . They must have arguments named x and value , and must return the modified object. For example, the following function modifies the second element of a vector:

Replacement functions are used by placing the function call on the left side of <- :

I say they act like they modify their arguments in place, because, as explained in Section 2.5 , they actually create a modified copy. We can see that by using tracemem() :

If your replacement function needs additional arguments, place them between x and value , and call the replacement function with additional arguments on the left:

When you write modify(x, 1) <- 10 , behind the scenes R turns it into:

Combining replacement with other functions requires more complex translation. For example:

is translated into:

(Yes, it really does create a local variable named *tmp* , which is removed afterwards.)

6.8.5 Special forms

Finally, there are a bunch of language features that are usually written in special ways, but also have prefix forms. These include parentheses:

  • (x) ( `(`(x) )
  • {x} ( `{`(x) ).

The subsetting operators:

  • x[i] ( `[`(x, i) )
  • x[[i]] ( `[[`(x, i) )

And the tools of control flow:

  • if (cond) true ( `if`(cond, true) )
  • if (cond) true else false ( `if`(cond, true, false) )
  • for(var in seq) action ( `for`(var, seq, action) )
  • while(cond) action ( `while`(cond, action) )
  • repeat expr ( `repeat`(expr) )
  • next ( `next`() )
  • break ( `break`() )

Finally, the most complex is the function function:

  • function(arg1, arg2) {body} ( `function`(alist(arg1, arg2), body, env) )

Knowing the name of the function that underlies a special form is useful for getting documentation: ?( is a syntax error; ?`(` will give you the documentation for parentheses.

All special forms are implemented as primitive functions (i.e. in C); this means printing these functions is not informative:

6.8.6 Exercises

Rewrite the following code snippets into prefix form:

Clarify the following list of odd function calls:

Explain why the following code fails:

Create a replacement function that modifies a random location in a vector.

Write your own version of + that pastes its inputs together if they are character vectors but behaves as usual otherwise. In other words, make this code work:

Create a list of all the replacement functions found in the base package. Which ones are primitive functions? (Hint: use apropos() .)

What are valid names for user-created infix functions?

Create an infix xor() operator.

Create infix versions of the set functions intersect() , union() , and setdiff() . You might call them %n% , %u% , and %/% to match conventions from mathematics.

6.9 Quiz answers

The three components of a function are its body, arguments, and environment.

f1(1)() returns 11.

You’d normally write it in infix style: 1 + (2 * 3) .

Rewriting the call to mean(c(1:10, NA), na.rm = TRUE) is easier to understand.

No, it does not throw an error because the second argument is never used so it’s never evaluated.

See Sections 6.8.3 and 6.8.4 .

You use on.exit() ; see Section 6.7.4 for details.

Advanced R Solutions

5 functions, 5.1 function fundamentals.

Q1 : Given a name, like "mean" , match.fun() lets you find a function. Given a function, can you find its name? Why doesn’t that make sense in R?

A : In R there is no one-to-one mapping between functions and names. A name always points to a single object, but an object may have zero, one or many names.

Let’s look at an example:

While the function in the first line is not bound to a name multiple names ( f1 , f2 and f3 ) point to the second function. So, the main point is that the relation between name and object is only clearly defined in one direction.

Besides that, there are obviously ways to search for function names. However, to be sure to find the right one(s), you should not only compare the code (body) but also the arguments (formals) and the creation environment. As formals() , body() and environment() all return NULL for primitive functions, the easiest way to check if two functions are exactly equal is just to use identical() .

Q2 : It’s possible (although typically not useful) to call an anonymous function. Which of the two approaches below is correct? Why?

A : The second approach is correct.

The anonymous function function(x) 3 is surrounded by a pair of parentheses before it is called by () . These extra parentheses separate the function call from the anonymous function’s body. Without them a function with the invalid body 3() is returned, which throws an error when we call it. This is easier to see if we name the function:

Q3 : A good rule of thumb is that an anonymous function should fit on one line and shouldn’t need to use {} . Review your code. Where could you have used an anonymous function instead of a named function? Where should you have used a named function instead of an anonymous function?

A : The use of anonymous functions allows concise and elegant code in certain situations. However, they miss a descriptive name and when re-reading the code, it can take a while to figure out what they do. That’s why it’s helpful to give long and complex functions a descriptive name. It may be worthwhile to take a look at your own projects or other people’s code to reflect on this part of your coding style.

Q4 : What function allows you to tell if an object is a function? What function allows you to tell if a function is a primitive function?

A : Use is.function() to test if an object is a function. Consider using is.primitive() to test specifically for primitive functions.

Q5 : This code makes a list of all functions in the {base} package.

Use it to answer the following questions:

Which base function has the most arguments?

How many base functions have no arguments? What’s special about those functions?

How could you adapt the code to find all primitive functions?

A : Let’s look at each sub-question separately:

To find the function with the most arguments, we first compute the length of formals() .

Then we sort n_args in decreasing order and look at its first entries.

We can further use n_args to find the number of functions with no arguments:

However, this over counts because formals() returns NULL for primitive functions, and length(NULL) is 0. To fix this, we can first remove the primitive functions:

Indeed, most of the functions with no arguments are actually primitive functions.

To find all primitive functions, we can change the predicate in Filter() from is.function() to is.primitive() :

Q6 : What are the three important components of a function?

A : These components are the function’s body() , formals() and environment() . However, as mentioned in Advanced R :

There is one exception to the rule that functions have three components. Primitive functions, like sum() , call C code directly with .Primitive() and contain no R code. Therefore, their formals() , body() , and environment() are all NULL .

Q7 : When does printing a function not show what environment it was created in?

A : Primitive functions and functions created in the global environment do not print their environment.

5.2 Lexical scoping

Q1 : What does the following code return? Why? Describe how each of the three c ’s is interpreted.

A : This code returns a named numeric vector of length one — with one element of the value 10 and the name "c" . The first c represents the c() function, the second c is interpreted as a (quoted) name and the third c as a value.

Q2 : What are the four principles that govern how R looks for values?

A : R’s lexical scoping rules are based on these four principles:

  • Name masking
  • Functions vs. variables
  • A fresh start
  • Dynamic lookup

Q3 : What does the following function return? Make a prediction before running the code yourself.

A : Within this nested function two more functions also named f are defined and called. Because the functions are each executed in their own environment R will look up and use the functions defined last in these environments. The innermost f() is called last, though it is the first function to return a value. Therefore, the order of the calculation passes “from the inside to the outside” and the function returns ((10 ^ 2) + 1) * 2 , i.e. 202.

5.3 Lazy evaluation

Q1 : What important property of && makes x_ok() work?

What is different with this code? Why is this behaviour undesirable here?

A : In summary: && short-circuits which means that if the left-hand side is FALSE it doesn’t evaluate the right-hand side (because it doesn’t matter). Similarly, if the left-hand side of || is TRUE it doesn’t evaluate the right-hand side.

We expect x_ok() to validate its input via certain criteria: it must not be NULL , have length 1 and be greater than 0 . Meaningful outcomes for this assertion will be TRUE , FALSE or NA . The desired behaviour is reached by combining the assertions through && instead of & .

&& does not perform elementwise comparisons; instead it uses the first element of each value only. It also uses lazy evaluation, in the sense that evaluation “proceeds only until the result is determined” (from ?Logic ). This means that the RHS of && won’t be evaluated if the LHS already determines the outcome of the comparison (e.g. evaluate to FALSE ). This behaviour is also known as “short-circuiting.” For some situations ( x = 1 ) both operators will lead to the same result. But this is not always the case. For x = NULL , the && -operator will stop after the !is.null statement and return the result. The following conditions won’t even be evaluated! (If the other conditions are also evaluated (by the use of & ), the outcome would change. NULL > 0 returns logical(0) , which is not helpful in this case.)

We can also see the difference in behaviour, when we set x = 1:3 . The && -operator returns the result from length(x) == 1 , which is FALSE . Using & as the logical operator leads to the (vectorised) x > 0 condition being evaluated and also returned.

Q2 : What does this function return? Why? Which principle does it illustrate?

A : The function returns 100. The default argument ( x = z ) gets lazily evaluated within the function environment when x gets accessed. At this time z has already been bound to the value 100 . The illustrated principle here is lazy evaluation .

Q3 : What does this function return? Why? Which principle does it illustrate?

A : The function returns c(2, 1) which is due to name masking . When x is accessed within c() , the promise x = {y <- 1; 2} is evaluated inside f1() ’s environment. y gets bound to the value 1 and the return value of {() ( 2 ) gets assigned to x . When y gets accessed next within c() , it has already the value 1 and R doesn’t need to look it up any further. Therefore, the promise y = 0 won’t be evaluated. Also, as y is assigned within f1() ’s environment, the value of the global variable y is left untouched.

Q4 : In hist() , the default value of xlim is range(breaks) , the default value for breaks is "Sturges" , and

Explain how hist() works to get a correct xlim value.

A : The xlim argument of hist() defines the range of the histogram’s x-axis. In order to provide a valid axis xlim must contain a numeric vector of exactly two unique values. Consequently, for the default xlim = range(breaks) ), breaks must evaluate to a vector with at least two unique values.

During execution hist() overwrites the breaks argument. The breaks argument is quite flexible and allows the users to provide the breakpoints directly or compute them in several ways. Therefore, the specific behaviour depends highly on the input. But hist ensures that breaks evaluates to a numeric vector containing at least two unique elements before xlim is computed.

Q5 : Explain why this function works. Why is it confusing?

A : Before show_time() accesses x (default stop("Error") ), the stop() function is masked by function(...) Sys.time() . As default arguments are evaluated in the function environment, print(x) will be evaluated as print(Sys.time()) .

This function is confusing because its behaviour changes when x ’s value is supplied directly. Now the value from the calling environment will be used and the overwriting of stop() won’t affect x anymore.

Q6 : How many arguments are required when calling library() ?

A : library() doesn’t require any arguments. When called without arguments library() invisibly returns a list of class libraryIQR , which contains a results matrix with one row and three columns per installed package. These columns contain entries for the name of the package (“Package”), the path to the package (“LibPath”) and the title of the package (“Title”). library() also has its own print method ( print.libraryIQR() ), which displays this information conveniently in its own window.

This behaviour is also documented under the details section of library() ’s help page ( ?library ):

If library is called with no package or help argument, it lists all available packages in the libraries specified by lib.loc, and returns the corresponding information in an object of class “libraryIQR.” (The structure of this class may change in future versions.) Use .packages(all = TRUE) to obtain just the names of all available packages, and installed.packages() for even more information.

Because the package and help argument from library() do not show a default value, it’s easy to overlook the possibility to call library() without these arguments. (Instead of providing NULL s as default values library() uses missing() to check if these arguments were provided.)

5.4 ... (dot-dot-dot)

Q1 : Explain the following results:

A : Let’s inspect the arguments and their order for both functions. For sum() these are ... and na.rm :

For the ... argument sum() expects numeric, complex, or logical vector input (see ?sum ). Unfortunately, when ... is used, misspelled arguments (!) like na.omit won’t raise an error (in case of no further input checks). So instead, na.omit is treated as a logical and becomes part of the ... argument. It will be coerced to 1 and be part of the sum. All other arguments are left unchanged. Therefore sum(1, 2, 3) returns 6 and sum(1, 2, 3, na.omit = TRUE) returns 7 .

In contrast, the generic function mean() expects x , trim , na.rm and ... for its default method.

As na.omit is not one of mean() ’s named arguments ( x ; and no candidate for partial matching), na.omit again becomes part of the ... argument. However, in contrast to sum() the elements of ... are not “part” of the mean. The other supplied arguments are matched by their order, i.e.  x = 1 , trim = 2 and na.rm = 3 . As x is of length 1 and not NA , the settings of trim and na.rm do not affect the calculation of the mean. Both calls ( mean(1, 2, 3) and mean(1, 2, 3, na.omit = TRUE) ) return 1 .

Q2 : Explain how to find the documentation for the named arguments in the following function call:

error target of assignment expands to non language object

A : First we type ?plot in the console and check the “Usage” section which contains:

The arguments we want to learn more about ( col , pch , xlab , col.lab ) are part of the ... argument. There we can find information for the xlab argument and a recommendation to visit ?par for the other arguments. Under ?par we type “col” into the search bar, which leads us to the section “Color Specification.” We also search for the pch argument, which leads to the recommendation to check ?points . Finally, col.lab is also directly documented within ?par .

Q3 : Why does plot(1:10, col = "red") only colour the points, not the axes or labels? Read the source code of plot.default() to find out.

A : To learn about the internals of plot.default() we add browser() to the first line of the code and interactively run plot(1:10, col = "red") . This way we can see how the plot is built and learn where the axes are added.

This leads us to the function call

The localTitle() function was defined in the first lines of plot.default() as:

The call to localTitle() passes the col parameter as part of the ... argument to title() . ?title tells us that the title() function specifies four parts of the plot: Main (title of the plot), sub (sub-title of the plot) and both axis labels. Therefore, it would introduce ambiguity inside title() to use col directly. Instead, one has the option to supply col via the ... argument, via col.lab or as part of xlab in the form xlab = list(c("index"), col = "red") (similar for ylab ).

5.5 Exiting a function

Q1 : What does load() return? Why don’t you normally see these values?

A : load() loads objects saved to disk in .Rdata files by save() . When run successfully, load() invisibly returns a character vector containing the names of the newly loaded objects. To print these names to the console, one can set the argument verbose to TRUE or surround the call in parentheses to trigger R’s auto-printing mechanism.

Q2 : What does write.table() return? What would be more useful?

A : write.table() writes an object, usually a data frame or a matrix, to disk. The function invisibly returns NULL . It would be more useful if write.table() would (invisibly) return the input data, x . This would allow to save intermediate results and directly take on further processing steps without breaking the flow of the code (i.e. breaking it into different lines). One package which uses this pattern is the {readr} package, 12 which is part of the tidyverse-ecosystem .

Q3 : How does the chdir parameter of source() compare to with_dir() ? Why might you prefer one to the other?

A : The with_dir() approach was given in Advanced R as:

with_dir() takes a path for a working directory ( dir ) as its first argument. This is the directory where the provided code ( code ) should be executed. Therefore, the current working directory is changed in with_dir() via setwd() . Then, on.exit() ensures that the modification of the working directory is reset to the initial value when the function exits. By passing the path explicitly, the user has full control over the directory to execute the code in.

In source() the code is passed via the file argument (a path to a file). The chdir argument specifies if the working directory should be changed to the directory containing the file. The default for chdir is FALSE , so you don’t have to provide a value. However, as you can only provide TRUE or FALSE , you are also less flexible in choosing the working directory for the code execution.

Q4 : Write a function that opens a graphics device, runs the supplied code, and closes the graphics device (always, regardless of whether or not the plotting code works).

A : To control the graphics device we use pdf() and dev.off() . To ensure a clean termination on.exit() is used.

Q5 : We can use on.exit() to implement a simple version of capture.output() .

Compare capture.output() to capture.output2() . How do the functions differ? What features have I removed to make the key ideas easier to see? How have I rewritten the key ideas to be easier to understand?

A : Using body(capture.output) we inspect the source code of the original capture.output() function: The implementation for capture.output() is quite a bit longer (39 lines vs. 7 lines).

In capture_output2() the code is simply forced, and the output is caught via sink() in a temporary file. An additional feature of capture_output() is that one can also capture messages by setting type = "message" . As this is internally forwarded to sink() , this behaviour (and also sink() ’s split argument) could be easily introduced within capture_output2() as well.

The main difference is that capture.output() calls print, i.e. compare the output of these two calls:

5.6 Function forms

Q1 : Rewrite the following code snippets into prefix form:

A : Let’s rewrite the expressions to match the exact syntax from the code above. Because prefix functions already define the execution order, we may omit the parentheses in the second expression.

Q2 : Clarify the following list of odd function calls:

A : None of these functions provides a ... argument. Therefore, the function arguments are first matched exactly, then via partial matching and finally by position. This leads us to the following explicit function calls:

Q3 : Explain why the following code fails:

A : First, let’s define x and recall the definition of modify() from Advanced R :

R internally transforms the code, and the transformed code reproduces the error above:

The error occurs during the assignment because no corresponding replacement function, i.e.  get<- , exists for get() . To confirm this, we reproduce the error via the following simplified example.

Q4 : Create a replacement function that modifies a random location in a vector.

A : Let’s define random<- like this:

Q5 : Write your own version of + that pastes its inputs together if they are character vectors but behaves as usual otherwise. In other words, make this code work:

A : To achieve this behaviour, we need to override the + operator. We need to take care to not use the + operator itself inside of the function definition, as this would lead to an undesired infinite recursion. We also add b = 0L as a default value to keep the behaviour of + as a unary operator, i.e. to keep + 1 working and not throwing an error.

Q6 : Create a list of all the replacement functions found in the {base} package. Which ones are primitive functions? (Hint use apropos() )

A : The hint suggests to look for functions with a specific naming pattern: Replacement functions conventionally end on “<-.” We can search for these objects by supplying the regular expression "<-$" to apropos() . apropos() also allows to return the position on the search path ( search() ) for each of its matches via setting where = TRUE . Finally, we can set mode = function to narrow down our search to relevant objects only. This gives us the following statement to begin with:

To restrict repl to names of replacement functions from the {base} package, we select only matches containing the relevant position on the search path.

To find out which of these functions are primitives, we first search for these functions via mget() and then subset the result using Filter() and is.primitive() .

Overall the {base} package contains 62 replacement functions of which 17 are primitive functions.

Q7 : What are valid names for user-created infix functions?

A : Let’s cite from the section on function forms from Advanced R :

… names of infix functions are more flexible than regular R functions: they can contain any sequence of characters except “%.”

Q8 : Create an infix xor() operator.

A : We could create an infix %xor% like this:

Q9 : Create infix versions of the set functions intersect() , union() , and setdiff() . You might call them %n% , %u% , and %/% to match conventions from mathematics.

A : These infix operators could be defined in the following way. ( %/% is chosen instead of %\% , because \ serves as an escape character.)

IMAGES

  1. R Error: target of assignment expands to non-language object (Example)

    error target of assignment expands to non language object

  2. R如何正确动态创建变量名,解决target of assignment expands to non-language object-CSDN博客

    error target of assignment expands to non language object

  3. SyntaxError: Invalid destructuring assignment target in JS

    error target of assignment expands to non language object

  4. SyntaxError: Invalid destructuring assignment target in JS

    error target of assignment expands to non language object

  5. Local variable referenced before assignment Solved error in Python

    error target of assignment expands to non language object

  6. Classification of target assignment methods.

    error target of assignment expands to non language object

VIDEO

  1. Java Programming # 44

COMMENTS

  1. r - Error in : target of assignment expands to non-language ...

    get("x") <- 1 ## Error in get("x") <- 1 : ## target of assignment expands to non-language object The solution is either. assign("x", 1) or simply "x" <- 1 Using get() with replacement functions deals with a more complex case of get combined with a replacement function.

  2. R Error: target of assignment expands to non-language object ...

    In this article, you’ll learn how to handle the Error in X : target of assignment expands to non-language object in the R programming language. The content is structured as follows: 1) Example 1: Reproduce the Error in X : target of assignment expands to non-language object

  3. target of assignment expands to non-language object ERROR ...

    I am trying to assign model results to an object in a programmatic way so that I would only need to change the model run number to view particular model run results. However I am getting error message of "target of assignment expands to non-language object"

  4. Error in R – target of assignment expands to non-language ...

    In this tutorial you’ll learn how to avoid the Error in X : target of assignment expands to non-language object in the R programming language. Example 1: Replicate the Error in X – target of assignment expands to non-language object. # Error in 1:3 <- 10 : target of assignment expands to non-language object.

  5. How to Solve the R Error: attempt to apply non-function

    Handling ‘Target of Assignment Expands to Non-Language Object’ in R. When R presents this message, it often signifies a syntactical mistake with the assignment operator. Double-check that the left-hand side of an assignment is a valid language object in R, such as a variable name, and is not inadvertently a function call or other structure.

  6. R error target of assignment expands to non-language object

    Error: target of assignment expands to non-language object. In the event you get this error message, just change the name of the file you are trying to read with readxl. My scenario had files named 2020-ref… and by changing the name of the file to remove the hyphen and also move the numbers to the end of the file name, I was able to resolve ...

  7. Error: Target of assignment expands to non-language object ...

    Instead, you need to perform [[ subsetting rather than $ subsetting: Simply put, the syntactic form foo[['bar']] is (more or less) equivalent to foo$bar, where bar is a quoted string in the first expression, but an unquoted name in the second one.

  8. 6 Functions | Advanced R

    modify (get ("x"), 1) <-10 #> Error: target of assignment expands to non-language object Create a replacement function that modifies a random location in a vector. Write your own version of + that pastes its inputs together if they are character vectors but behaves as usual otherwise.

  9. Error in colnames: target of assignment expands to non ...">[R] Error in colnames: target of assignment expands to non ...

    Hi there, I cannot find a detailed explanation to the following error message: > colnames(matrix(1:10, ncol = 2)) <- c("X", "Y") Error in colnames(matrix(1:10, ncol = 2)) <- c("X", "Y") : target of assignment expands to non-language object However, when I do the following things, the error message disappear: > z <- matrix(1:10, ncol = 2 ...

  10. Advanced R Solutions - Rbind">5 Functions | Advanced R Solutions - Rbind

    get ("x") <-`modify<-` (get ("x"), 1, 10) #> Error in get("x") <- `modify<-`(get("x"), 1, 10) : #> target of assignment expands to non-language object The error occurs during the assignment because no corresponding replacement function, i.e. get<- , exists for get() .