How to Fix: names do not match previous names in R
Last Updated :
21 Feb, 2022
In this article, we are going to solve the error “names do not match previous names” in R Programming Language.
Generally, this error is produced due to the columns name not matching while combing several vectors, dataframe.
How to produce the error?
Here we have created two dataframe with 4 different column names(num, course, Marks, Subject) while using rbind() will occur the error.
R
val1 <- data.frame ( "num" = c (77,55,80,60),
"course" = c ( 'DSA' , 'C++' , 'R' , 'Python' ))
print (val1)
val2 <- data.frame ( "Marks" = c (23,45,81,80),
"Subject" = c ( 'COA' , 'OS' , 'SE' , 'AI' ))
print (val2)
rbind (val1,val2)
|
Output:
num course
1 77 DSA
2 55 C++
3 80 R
4 60 Python
Marks Subject
1 23 COA
2 45 OS
3 81 SE
4 80 AI
Error in match.names(clabs, names(xi)): names do not match previous names
How to solve this error
Method 1: Changes columns name
To solve this error we have to change the columns name, for this, we will create the third dataframe and copy the second dataframe into it, and copy the columns from the first dataframe as shown in the below code.
R
val1 <- data.frame ( "num" = c (77,55,80,60),
"course" = c ( 'DSA' , 'C++' , 'R' , 'Python' ))
val2 <- data.frame ( "Marks" = c (23,45,81,80),
"Subject" = c ( 'COA' , 'OS' , 'SE' , 'AI' ))
val3 <- val2
colnames (val3) <- colnames (val1)
rbind (val1,val3)
|
Output:
num course
77 DSA
55 C++
80 R
60 Python
23 COA
45 OS
81 SE
80 AI
Method 2: Rename Columns name
We can rename the columns name to solve this error, for this we will copy the columns into 2nd dataframe.
R
val1 <- data.frame ( "num" = c (77,55,80,60),
"course" = c ( 'DSA' , 'C++' , 'R' , 'Python' ))
val2 <- data.frame ( "Marks" = c (23,45,81,80),
"Subject" = c ( 'COA' , 'OS' , 'SE' , 'AI' ))
names (val2) <- names (val1)
rbind (val1, val2)
|
Output:
77 DSA
55 C++
80 R
60 Python
23 COA
45 OS
81 SE
80 AI
Method 3: Using dplyr package
Here we will use bind_rows() methods from the dplyr package, it will create each column along with the existing value if the dataframe has no element into it then it saves as NA elements.
R
library ( "dplyr" )
val1 <- data.frame ( "num" = c (77,55,80,60),
"course" = c ( 'DSA' , 'C++' , 'R' , 'Python' ))
val2 <- data.frame ( "Marks" = c (23,45,81,80),
"Subject" = c ( 'COA' , 'OS' , 'SE' , 'AI' ))
bind_rows (val1, val2)
|
Output:
num course Marks Subject
77 DSA NA NA
55 C++ NA NA
80 R NA NA
60 Python NA NA
NA NA 23 COA
NA NA 45 OS
NA NA 81 SE
NA NA 80 AI
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...