我有一个CSV文件
Market,CampaignName
Wells Fargo,Gary IN MetroChicago IL Metro
EMC,Los Angeles CA MetroBoston MA Metro
Apple,Cupertino CA Metro
使用的部分代码是
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]
输出
[,1] [,2]
Wells Fargo "Gary" "IN"
Wells Fargo "Chicago" "IL"
EMC "Los Angeles" "CA"
EMC "Boston" "MA"
Apple "Cupertino" "CA"
将所需的输出发送到CSV文件,第一行作为标题
Market,City,State
Wells Fargo,Gary,IN
Wells Fargo,Chicago,IL
EMC,Los Angeles,CA
EMC,Boston,MA
Apple,Cupertino,CA
如何将输出写入R中的CSV文件? R的新人。
答案 0 :(得分:0)
很难说出你到底发生了什么。也许最好的情况是自己编写标题然后写入你的矩阵。如果您的对象是矩阵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)
生成的文件如下所示:
Market,City,State
Wells Fargo,Gary,IN
Wells Fargo,Chicago,IL
EMC,Los Angeles,CA
EMC,Boston,MA
Apple,Cupertino,CA