R Error in apply(data) : dim(X) must have a positive length
In this article you’ll learn how to avoid the “Error in apply : dim(X) must have a positive length” in the R programming language.
The post is structured as follows:
Let’s just jump right in…
Introduction of Example Data
The following data is used as basement for this R programming tutorial:
data <- data.frame(x1 = 1:7, # Create example data x2 = 8:2) data # Print example data
Have a look at the table that got returned by the previous syntax. It reveals that our example data consists of seven rows and two columns.
Example 1: Reproduce the Error in apply : dim(X) must have a positive length
The following R code explains how to replicate the “Error in apply : dim(X) must have a positive length”.
apply(data$x1, 2, mean) # Trying to use apply function # Error in apply(data$x1, 2, mean) : dim(X) must have a positive length
Unfortunately, the RStudio console returns the error message “Error in apply : dim(X) must have a positive length”.
The reason for this is that we have tried to use a vector (i.e. the column vector x1) as input for the apply function. However, the apply function takes only entire data tables as input.
Next, I’ll explain how to fix this issue.
Example 2: Solve the Error in apply : dim(X) must have a positive length
In Example 2, I’ll illustrate how to deal with the “Error in apply : dim(X) must have a positive length”.
We basically have two solutions for our problem.
1) We can use the apply function to return the mean of all variables in our data frame:
apply(data, 2, mean) # Properly using apply # x1 x2 # 4 5
2) we can use only the mean function to return the mean of only one variable:
mean(data$x1) # Using mean function instead #  4
No matter which alternative you choose, keep in mind that the apply function can not be used for one-dimensional data.
Video & Further Resources
Have a look at the following video instruction of my YouTube channel. In the video, I’m explaining the R programming codes of this article:
The YouTube video will be added soon.
Furthermore, you may want to read some of the other articles of my homepage.
- Error in hist.default : ‘x’ must be numeric
- Error in as.Date.numeric(X) : ‘origin’ must be supplied
- Error in scan: Line 1 did not have X Elements
- ggplot2 Error: Aesthetics must be either length 1 or the same as the data
- Warnings & Errors in R (List with Examples)
- R Programming Overview
Summary: In this article you have learned how to handle the “Error in apply : dim(X) must have a positive length” in the R programming language. Please tell me about it in the comments, in case you have any further comments or questions.