Search code examples
rstringconcatenation

Concatenate numbers into strings R programming


I have two columns which contain numeric values. I would like to create a third by concatenating them as a string. I do that using the paste function. but on exporting the data to CSV. The third column gets converted into date Desired output (Column C):

A      B     C
2      3     2-3
4      5     4-5

A & B is contained in a dataset called concat code written till now as under

concat$C <- paste(concat$A,concat$B, sep="-", collapse = NULL)

This shows the desired output on screen but on writing to CSV, values in C column changes to date format.


Solution

  • As the comments have pointed out this a result of the way Excel (or other applications) interpret column formats. Similar problems happen if you want to export numeric columns with leading 0s, open US-format csv in countries like Germany, etc.

    The easiest solution to all these problems is to not open .csv in Excel directly.

    Instead open a new, empty Excel and use the Import Assistant in the data tab. This will allow you to import csv or any other separated-text-format and control the column formats before importing!

    Be aware that simply opening .csv,.tsv, etc. in Exel and then saving in the original file format will overwrite all data to the Excel assumed data format! So always use the import assistant.