0

I have a CSV file

Market,CampaignName
Wells Fargo,Gary IN MetroChicago IL Metro
EMC,Los Angeles CA MetroBoston MA Metro
Apple,Cupertino CA Metro

The partial code used is

library(stringr)
xx.to.split <- with(xx, setNames(gsub("Metro", "", as.character(CampaignName)), Market))
do.call(rbind, str_match_all(xx.to.split, "(.+?) ([A-Z]{2}) ?"))[, -1]

The output is

                                [,1]          [,2]
                    Wells Fargo "Gary"        "IN"
                    Wells Fargo "Chicago"     "IL"
                    EMC         "Los Angeles" "CA"
                    EMC         "Boston"      "MA"
                    Apple       "Cupertino"   "CA"

And the desired output to the CSV file with the first row as the headers

Market,City,State
Wells Fargo,Gary,IN
Wells Fargo,Chicago,IL
EMC,Los Angeles,CA
EMC,Boston,MA
Apple,Cupertino,CA

How to write the output to a CSV file in R? New to R.

4
  • 2
    write.csv(data, "data.csv")
    – Rorschach
    Feb 26, 2014 at 4:12
  • This question is a result of this question. Look into write.csv via help(write.csv). Feb 26, 2014 at 4:16
  • @BlueMagister :How to include the headers as specified in the desired output? I have clearly specified the desired result and the result that I am getting. Feb 26, 2014 at 4:24
  • @BlueMagister The format is not right and so not getting the right answer Feb 26, 2014 at 4:25

1 Answer 1

0

Hard to tell what exactly you're getting at. Maybe the best case is to write the header yourself and then write in the matrix you have. If your object is a matrix m:

ff <- file("filename.csv", open = "wt")
writeLines("Market,City,State", con = ff)
write.table(m, file = ff, sep = ",", row.names = TRUE, 
  col.names = FALSE, quote = FALSE)
close(ff)

The resulting file looks like:

Market,City,State
Wells Fargo,Gary,IN
Wells Fargo,Chicago,IL
EMC,Los Angeles,CA
EMC,Boston,MA
Apple,Cupertino,CA
2
  • The first column of the 'Market' never really shows up in the CSV file? How to write to the CSv file the 'Market' Column as well? Feb 26, 2014 at 4:55
  • That should be handled with row.names = TRUE. I've edited my answer to show what the resulting file looks like for me. If this isn't working for you, please tell me what you get by editing your question. Feb 26, 2014 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.