How to Fix in R: object of type ‘closure’ is not subsettable
Last Updated :
06 Apr, 2022
In this article, we will discuss how to fix the “object of type ‘closure’ is not subsettable” error in the R programming language.
The error that one may face in R is:
object of type 'closure' is not subsettable
The R compiler produces such an error when we try to subset a function. In R, we can subset a list, vector, etc but a function having a type ‘closure that can’t be subsetted.
When this error might occur:
Consider that we have a function in R that takes each element of a vector as input and add it with 10:
R
Add <- function (x) {
x <- x + 10
return (x)
}
|
Let’s add some menu driver code that can call this function:
R
Add <- function (vect) {
vect <- vect + 10
return (vect)
}
vect <- c (8, 9, 12, 14, 20)
Add (vect)
|
Output:
As you can see in the output, each element of the vector is added with 10. Now, suppose we try to subset this function:
R
Add <- function (vect) {
vect <- vect + 10
return (vect)
}
vect <- c (8, 9, 12, 14, 20)
Add[2]
|
Output:
The compiler produces such an error because it is not allowed to subset an object having the type closure in R. In order to confirm that the function is of type closure we can use the typeof() function that has the following syntax:
Syntax: typeof(x)
Parameters:
x: It represents the specified data
R
Add <- function (vect) {
vect <- vect + 10
return (vect)
}
vect <- c (8, 9, 12, 14, 20)
typeof (Add)
|
Output:
Any function in R is of type closure. For example, let’s try to subset a median() inbuilt function first:
Syntax: median(x)
Parameter: x: a vector
Return Type: Returns the median of vector elements
Output:
Now we will subset the range() inbuilt function:
Syntax: range(x)
Parameter: x: a vector
Return Type: Returns a range
Output:
How to fix this error:
We can fix this error easily by not subsetting the function. For example, suppose we want to use the Add() function for the second element of the vector vect:
R
Add <- function (vect) {
vect <- vect + 10
return (vect)
}
vect <- c (8, 9, 12, 14, 20)
Add (vect[2])
|
Output:
This time the program compiled successfully because here we are subsetting the vector instead of the function. Also, note that we can apply the Add() on the entire vector:
R
Add <- function (vect) {
vect <- vect + 10
return (vect)
}
vect <- c (8, 9, 12, 14, 20)
Add (vect)
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...