san1
san1

Reputation: 515

how can we export data into mutiple csv files from a single df

I want to export city wise data to csv files, for that i am following a static method as below

city=c("NYC","NYC","NYC","LONDON","LONDON","LONDON","PARIS","PARIS")
country=c("USA","USA","USA","UK","UK","UK","FRANCE","FRANCE")
year=c(2000,2000,2000,2010,2010,2010,2017,2017)
df=data.frame(city,country,year)

#1
city<-df[which(df$city == "NYC"),]
file_name = paste0("NYC",".csv")
write.csv(city,file_name,row.names=FALSE)

#2
city<-df[which(df$city == "LONDON"),]
file_name = paste0("LONDON",".csv")
write.csv(city,file_name,row.names=FALSE)

same for #3
Please help it to convert into dynamic code. Thanks in advance

Upvotes: 0

Views: 46

Answers (3)

Antonios
Antonios

Reputation: 1939

you can also use split to break your df in a list and then loop:

for (i in split(df,city)){
  write.csv(i,paste0(i$city[1],".csv"))
}

Upvotes: 1

rosscova
rosscova

Reputation: 5580

@snoram's answer should work well, so please consider this just another way to do the same thing. I'm a fan of data.table, and one of the things I like about it is calling functions alongside a by call:

library( data.table )
setDT( df )

df[ , write.csv( .SD,
                 paste0( city[1], ".csv" ),
                 row.names = FALSE ),
    by = city ]

.SD here represents each subset of df; one for each value of city.

city[1] takes the first value of city from each .SD (that column will be filled with one value all the way down).

Upvotes: 1

s_baldur
s_baldur

Reputation: 33498

I would do something like:

for (cit in unique(df$city)) {
  write.csv(
    x = subset(df, city == cit),
    file = paste0(cit, ".csv"),
    row.names = FALSE
  )
}

PS. Often lowercase filenames are preferred, thus I would convert file = paste0(cit, ".csv") to file = tolower(paste0(cit, ".csv"))

Upvotes: 2

Related Questions