How to Handle in R: object of type ‘closure’ is not subsettable


One error you may encounter in R is:

object of type 'closure' is not subsettable

This error occurs when you attempt to subset a function.

In R, it’s possible to subset lists, vectors, matrices, and data frames, but a function has the type ‘closure’ which cannot be subsetted.

This tutorial shares exactly how to address this error.

How to Reproduce the Error

Suppose we create the following function in R that takes each value in a vector and multiplies it by 5:

#define function
cool_function <- function(x) {
  x <- x*5
  return(x)
}

Here’s how we might use this function in practice:

#define data
data <- c(2, 3, 3, 4, 5, 5, 6, 9)

#apply function to data
cool_function(data)

[1] 10 15 15 20 25 25 30 45

Notice that each value in the original vector was multiplied by 5.

Now suppose we attempted to subset the function:

#attempt to get first element of function
cool_function[1]

Error in cool_function[1] : object of type 'closure' is not subsettable

We receive an error because it’s not possible to subset an object of type ‘closure’ in R.

We can use the following syntax to verify that the function is indeed of the type ‘closure’:

#print object type of function
typeof(cool_function)

[1] "closure"

More Examples of ‘Closure’ Objects

Any function in R is of the type ‘closure’. For example, we would receive this error if we attempted to subset any function in base R:

#attempt to subset mean function
mean[1]

Error in mean[1] : object of type 'closure' is not subsettable

#attempt to subset standard deviation function
sd[1]

Error in sd[1] : object of type 'closure' is not subsettable

#attempt to subset table function
tabld[1]

Error in table[1] : object of type 'closure' is not subsettable

How to Address the Error

The way to address this error is to simply avoid subsetting a function.

For example, if we’d like to apply our cool_function from earlier to only the first element in a vector, we can use the following syntax:

#apply function to just first element in vector
cool_function(data[1])

[1] 10

We don’t receive an error because we subsetted the vector instead of the function.

Or we could apply the cool_function to the entire vector:

#apply function to every element in vector
cool_function(data)

[1] 10 15 15 20 25 25 30 45

We don’t receive an error because we didn’t attempt to subset the function in any way.

Additional Resources

The following tutorials explain how to address other common errors in R:

How to Fix: the condition has length > 1 and only the first element will be used
How to Fix in R: dim(X) must have a positive length
How to Fix in R: missing value where true/false needed
How to Fix: NAs Introduced by Coercion

Leave a Reply

Your email address will not be published.