Handle Error in R: Replacement has X Rows Data has Y (2 Examples)
In this tutorial, I’ll explain how to deal with the error message “replacement has X rows, data has Y” in the R programming language.
Creation of Example Data
data(iris) # Example data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Example data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
Example 1: Replicating the Error Message: Replacement has X Rows, Data has Y
iris$new[which(iris$Sepal.Length < 5)] <- "small" # Creating new variables doesn't work # Error in `$<-.data.frame`(`*tmp*`, new, value = c(NA, "small", "small", : # replacement has 107 rows, data has 150 |
iris$new[which(iris$Sepal.Length < 5)] <- "small" # Creating new variables doesn't work # Error in `$<-.data.frame`(`*tmp*`, new, value = c(NA, "small", "small", : # replacement has 107 rows, data has 150
Example 2: Solving the Error Message: Replacement has X Rows, Data has Y
iris$new <- NA # Creating empty new variable first iris$new[which(iris$Sepal.Length < 5)] <- "small" # Adding values to variable head(iris) # Showing head of updated data in console # Sepal.Length Sepal.Width Petal.Length Petal.Width Species new # 1 5.1 3.5 1.4 0.2 setosa <NA> # 2 4.9 3.0 1.4 0.2 setosa small # 3 4.7 3.2 1.3 0.2 setosa small # 4 4.6 3.1 1.5 0.2 setosa small # 5 5.0 3.6 1.4 0.2 setosa <NA> # 6 5.4 3.9 1.7 0.4 setosa <NA> |
iris$new <- NA # Creating empty new variable first iris$new[which(iris$Sepal.Length < 5)] <- "small" # Adding values to variable head(iris) # Showing head of updated data in console # Sepal.Length Sepal.Width Petal.Length Petal.Width Species new # 1 5.1 3.5 1.4 0.2 setosa <NA> # 2 4.9 3.0 1.4 0.2 setosa small # 3 4.7 3.2 1.3 0.2 setosa small # 4 4.6 3.1 1.5 0.2 setosa small # 5 5.0 3.6 1.4 0.2 setosa <NA> # 6 5.4 3.9 1.7 0.4 setosa <NA>
Further Resources & Related Tutorials
You may find some related R programming tutorials on topics such as vectors, extracting data, and coding errors in the following list: