-1

I have two dataframes with me stored as ca13 and ca0112. I want to merge these two dataframes by column names using merge function. However, the column names are different.

I am trying to use a for loop to achieve this as

cnam0112 <- c(names(ca0112))
cname13 <- c(names(ca13))

for( i in 1:size ) { ca13 <- rename(ca13, cname13[i] = cnam0112[i]) }

I am getting the usual error Error: unexpected '=' in "for( i in 1:16) { ca13 <- rename(ca13, stuff13[i]="

What am I doing wrong? Individually naming each column name is time-consuming! I am just using the dplyr library. The column names are strings with spaces between them in one dataframe and . as a separator in the other.

[1] "State" "Year" "Cause"
[4] "Male.upto.14.years" "Male.15.29.years" "Male.30.44.years"
[7] "Male.45.59.years" "Male.60.years.and.above" "Total.Male"
[10] "Female.upto.14.years" "Female.15.29.years" "Female.30.44.years"
[13] "Female.45.59.years" "Female.60.years.and.above" "Total.Female"
[16] "Grand.Total"

[1] "State" "Year" "Cause"
[4] "Male upto 14 years" "Male 15-29 years" "Male 30-44 years"
[7] "Male 45-59 years" "Male 60 years and above" "Total Male"
[10] "Female upto 14 years" "Female 15-29 years" "Female 30-44 years"
[13] "Female 45-59 years" "Female 60 years and above" "Total Female"
[16] "Grand Total"

Rawshn
  • 37
  • 13

2 Answers2

2

I would advise you use janitor::clean_names on both data frames to get cleaner and easier to read names. Spaces and dots get replaced by underscores, and every column name gets set to lowercase. The names should then match.

brodrigues
  • 1,541
  • 2
  • 14
  • 19
1

Instead of using a loop, I could have used

ca13 <- setNames(ca13, names(ca0112))

Got the answer from the comments, thanks!

PKumar
  • 10,971
  • 6
  • 37
  • 52
Rawshn
  • 37
  • 13
  • read on how to answer so as the code may be seen as a chunk eg you need to space four times before writing the code – Onyambu Dec 24 '17 at 08:10