R Warning message: ‘newdata’ had N rows but variables found have M rows (2 Examples)
In this tutorial, I’ll illustrate how to avoid the “Warning message: ‘newdata’ had N rows but variables found have M rows” in R.
Creation of Example Data
data(iris) # Loading iris data set |
data(iris) # Loading iris data set
set.seed(6593947) # Split iris into two subsets split_dummy <- rbinom(nrow(iris), 1, prob = 0.3) |
set.seed(6593947) # Split iris into two subsets split_dummy <- rbinom(nrow(iris), 1, prob = 0.3)
a <- iris[split_dummy == 0, "Sepal.Length"] # First subset b <- iris[split_dummy == 0, "Sepal.Width"] |
a <- iris[split_dummy == 0, "Sepal.Length"] # First subset b <- iris[split_dummy == 0, "Sepal.Width"]
c <- iris[split_dummy == 1, "Sepal.Width"] # Second subset |
c <- iris[split_dummy == 1, "Sepal.Width"] # Second subset
iris_mod <- lm(a ~ b) # Applying lm() function |
iris_mod <- lm(a ~ b) # Applying lm() function
Example 1: Replicating the Warning: ‘newdata’ had N rows but variables found have M rows
predicted_values <- predict(iris_mod, data.frame(c)) # Applying predict() function # Warning message: # 'newdata' had 46 rows but variables found have 104 rows |
predicted_values <- predict(iris_mod, data.frame(c)) # Applying predict() function # Warning message: # 'newdata' had 46 rows but variables found have 104 rows
Example 2: Solving the Warning: ‘newdata’ had N rows but variables found have M rows
predicted_values <- predict(iris_mod, data.frame(b = c)) # Proper usage of predict() head(predicted_values) # Display predicted values in RStudio # 1 2 3 4 5 6 # 5.879750 5.819144 5.773690 5.803993 5.910052 5.773690 |
predicted_values <- predict(iris_mod, data.frame(b = c)) # Proper usage of predict() head(predicted_values) # Display predicted values in RStudio # 1 2 3 4 5 6 # 5.879750 5.819144 5.773690 5.803993 5.910052 5.773690
Related Tutorials & Further Resources
Please find some related tutorials on topics such as variables, loops, and extracting data in the following list: