R rbind() Error: names do not match previous names (2 Examples)
In this article you’ll learn how to solve the error of the rbing function “names do not match previous names” in R programming.
Example Data
my_df1 <- data.frame(col1 = 4:2, # Constructing data set No. 1 col2 = 7) my_df1 # Showing data set No. 1 in RStudio console # col1 col2 # 1 4 7 # 2 3 7 # 3 2 7 |
my_df1 <- data.frame(col1 = 4:2, # Constructing data set No. 1 col2 = 7) my_df1 # Showing data set No. 1 in RStudio console # col1 col2 # 1 4 7 # 2 3 7 # 3 2 7
my_df2 <- data.frame(col3 = 5:9, # Constructing data set No. 2 col4 = 2) my_df2 # Showing data set No. 2 in RStudio console # col3 col4 # 1 5 2 # 2 6 2 # 3 7 2 # 4 8 2 # 5 9 2 |
my_df2 <- data.frame(col3 = 5:9, # Constructing data set No. 2 col4 = 2) my_df2 # Showing data set No. 2 in RStudio console # col3 col4 # 1 5 2 # 2 6 2 # 3 7 2 # 4 8 2 # 5 9 2
Replicate the Error Message: names do not match previous names
rbind(my_df1, my_df2) # Trying to use rbind() function # Error in match.names(clabs, names(xi)) : # names do not match previous names |
rbind(my_df1, my_df2) # Trying to use rbind() function # Error in match.names(clabs, names(xi)) : # names do not match previous names
Solution 1: Harmonizing Column Names of Data Frames to Solve Error
my_df3 <- my_df2 # Duplicating data set No. 2 colnames(my_df3) <- colnames(my_df1) # Harmonizing column names my_df3 # Showing new data set in RStudio console # col1 col2 # 1 5 2 # 2 6 2 # 3 7 2 # 4 8 2 # 5 9 2 |
my_df3 <- my_df2 # Duplicating data set No. 2 colnames(my_df3) <- colnames(my_df1) # Harmonizing column names my_df3 # Showing new data set in RStudio console # col1 col2 # 1 5 2 # 2 6 2 # 3 7 2 # 4 8 2 # 5 9 2
rbind(my_df1, my_df3) # Using rbind() function again # col1 col2 # 1 4 7 # 2 3 7 # 3 2 7 # 4 5 2 # 5 6 2 # 6 7 2 # 7 8 2 # 8 9 2 |
rbind(my_df1, my_df3) # Using rbind() function again # col1 col2 # 1 4 7 # 2 3 7 # 3 2 7 # 4 5 2 # 5 6 2 # 6 7 2 # 7 8 2 # 8 9 2
Solution 2: Using bind_rows() Function of dplyr Package to Solve Error
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr package |
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr package
bind_rows(my_df1, my_df2) # Using bind_rows() dplyr function in R # col1 col2 col3 col4 # 1 4 7 NA NA # 2 3 7 NA NA # 3 2 7 NA NA # 4 NA NA 5 2 # 5 NA NA 6 2 # 6 NA NA 7 2 # 7 NA NA 8 2 # 8 NA NA 9 2 |
bind_rows(my_df1, my_df2) # Using bind_rows() dplyr function in R # col1 col2 col3 col4 # 1 4 7 NA NA # 2 3 7 NA NA # 3 2 7 NA NA # 4 NA NA 5 2 # 5 NA NA 6 2 # 6 NA NA 7 2 # 7 NA NA 8 2 # 8 NA NA 9 2