0

The 2 files have different column names and numbers. I would like to combine the rows of the first file under the rows of the second file for the related columns based on the positions of the columns. I tried the below:

  1. specifying the columns positions for the 2 files.

    one = df1[6:59, ]
    two = df2[2:55, ]
    
  2. binding the rows, using mutate because some for the columns contains factor data, not integers

    a= bind_rows(mutate_all(one, as.character), mutate_all(two, as.character))
    

but it didn't work! can anyone help, please?

Phil
  • 7,287
  • 3
  • 36
  • 66
Shereen
  • 3
  • 2
  • Please check out https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610 Shereen to see how to best ask questions so people can help you. A minimal reproducible example is generally desirable. – geotheory May 04 '20 at 15:45

1 Answers1

0

If you bind by column position you'll need rbind, but the objects will I think need same column names, so you'll need to reassign them with something like:

d1 = read_csv('file1.csv')
d2 = read_csv('file2.csv')
names(d2)[6:59] = names(d1)[2:55]

Then the data frames will need to have the same number of columns.

# rbind method
rbind(d1, d2)

A dplyr approach will work with any number of columns but again the column names will need to be match.

# dplyr method
dplyr::bind_rows(list(d1, d2))
geotheory
  • 22,624
  • 29
  • 119
  • 196
  • I tried it but, it didn't combine the raws because the "session" column data is an integer in one file, and is a factor in the other, so how to solve this problem? Also, the columns that exist in one sheet and not in the other will not exist in the final results, and still, I need them to be shown. can you still help :) ? – Shereen May 04 '20 at 15:17
  • R error regarding the session column is: Error: Column session can't be converted from factor to integer – Shereen May 04 '20 at 15:19
  • If you read in with `stringsToFactors=FALSE` or use `readr::read_csv()` or `mutate(colname = as.character(colname))` to change it should work :) – geotheory May 04 '20 at 15:36
  • Do not convert direclty from factor to integer! You have to go via character. – geotheory May 04 '20 at 15:37
  • OMG, finally it did work!! I spend like 4 hours and couldn't solve it before!! Thank so much geotheory :) – Shereen May 04 '20 at 16:04
  • Jolly good :) See my comment above about reproducible examples? – geotheory May 04 '20 at 16:51
  • Lastly, if it solves your problem please tick the answer to close the question :) – geotheory May 04 '20 at 18:57