How to Fix in R: replacement has X rows, data has Y


One error message you may encounter when using R is:

Error in `$<-.data.frame`(`*tmp*`, conf_full, value = c("West", "West",  : 
  replacement has 3 rows, data has 5

This error occurs when you attempt to add a new column to a data frame whose values are based on an existing column, but you fail to first create the new column.

The following example shows how to resolve this error in practice.

How to Reproduce the Error

Suppose we create the following data frame in R:

#create data frame
df <- data.frame(conference=c('W', 'W', 'W', 'E', 'E'),
                 points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34))	

#view data frame
df

  conference points assists
1          W     99      33
2          W     90      28
3          W     86      31
4          E     88      39
5          E     95      34

Now suppose we attempt to add a new column to the data frame called conf_full:

#attempt to create new column based on conference name
df$conf_full[which(df$conference=='W')] <- 'West'
df$conf_full[which(df$conference=='E')] <- 'East'

Error in `$<-.data.frame`(`*tmp*`, conf_full, value = c("West", "West",  : 
  replacement has 3 rows, data has 5

We receive an error because the variable name conf_full doesn’t yet exist, which means we can’t assign values to that column yet.

How to Avoid the Error

To avoid this error, we can first create the conf_full variable and simply assign values of NA to it:

#create conf_full variable
df$conf_full <- NA

Now that the variable exists, we can assign values to it:

#create new column based on conference
df$conf_full[which(df$conference=='W')] <- 'West'
df$conf_full[which(df$conference=='E')] <- 'East'

#view updated data frame
df

  conference points assists conf_full
1          W     99      33      West
2          W     90      28      West
3          W     86      31      West
4          E     88      39      East
5          E     95      34      East

Notice that we don’t receive any error this time because we first created the conf_full variable before attempting to assign values to it.

Additional Resources

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

How to Fix in R: Arguments imply differing number of rows
How to Fix in R: error in select unused arguments
How to Fix in R: replacement has length zero

Leave a Reply

Your email address will not be published.