Error in apply: dim(X) must have a positive length

Error in apply(data$x, 2, mean): dim(X) must have a positive length, In this post, you’ll discover how to prevent the R programming error.

When you try to use the apply() function to generate a metric for a column of a data frame or matrix but pass a vector as an argument instead of a data frame or matrix, you’ll get this error.

First, we need to create a data frame for illustration. Let’s create two variables x and y.

data <- data.frame(x = 1:9, y = 21:29)

Now we can load the data frame into the r console.

data                           
   x  y
1 1 21
2 2 22
3 3 23
4 4 24
5 5 25
6 6 26
7 7 27
8 8 28
9 9 29

Take a look at the data that the preceding syntax produced. It shows that our sample data has nine rows and two columns.

First, we need to reproduce the error in R console.

Reproduce the Error: dim(X) must have a positive length

The error in apply may be replicated using the R code below.

Let’s pretend we’re looking for the mean of the variable x in our sample data. Then, as demonstrated below, we may try using the apply and mean functions.

apply(data$x, 2, mean) 
Error in apply(data$x, 2, mean) : dim(X) must have a positive length

As you can see, the error notice appears in the RStudio console.

The reason for this is that we attempted to utilize a vector as input for the apply function (i.e. the column vector x). The apply function, on the other hand, only accepts full data tables as an input.

The apply() method must be applied to a data frame or matrix, however, we are attempting to apply it to a single column in the data frame, resulting in an error.

Let’s see how to resolve the problem.

Solution: Solve the Error

Here we have three solutions to solve this issue in R.

Approach 1:

To get the mean of all variables in our data frame, we may use the apply function.

Let’s see how to resolve the issue.

apply(data, 2, mean)           
x  y
5 25

Approach 2:-

Apply function allow us to find the mean of certain values in a data frame:

apply(data[c('x')], 2, mean)  
x
5

Approach 3:-

If you’re only interested in one variable, then you can make use of the mean function to get the variable’s mean.

mean(data$x)
[1] 5

Keep in mind that the apply function cannot be used with one-dimensional data, regardless of which option you choose.

QQ-plots in R: Quantile-Quantile Plots-Quick Start Guide »

Subscribe to our newsletter!

[newsletter_form type=”minimal”]

You may also like...

Leave a Reply

Your email address will not be published.

11 − 6 =

error

Subscribe Now