Check the correct arguments with ?write.csv
: write.table(x, file = "")
.
If I do not misunderstand, the idea should be to create the data frames first without necessarily including their paths for the filenames.
I guess you want to cycle through the unique city names, and not for every city name in the for()
loop.
Use well-formatted code in your next questions, please (with spaces -- you could also consult Google's R Style Guide).
Why do you use =
instead of <-
? Why do you use %in%
? Why do you use filter()
instead of subset()
?
Please consult the relevant function documentations (e.g.: ?filter
shows that this is not an appropriate function for what you want to do!)
The following stores each dataframe as an element of a list, for each city name.
It also saves a csv file for each data frame (each dataframe corresponds to a different city).
dataframe_temp = data.frame(ID = c(1, 1, 2, 3, 3),
City = c("a", "a", "b", "c", "c"),
Qty = c(20, 14, 40, 50, 60))
dataframe.list <- list()
# avoid hardcoded numbers as ", 2" as theses can
# change in the future, after e.g. an expansion of the dataframe!
for (city in unique(dataframe_temp$City)) {
print(city)
dataframe.list[[i]] = subset(dataframe_temp, City == city)
# use your folder location instead of "~/"
write.csv(x = dataframe.list[[i]], file = paste0("~/", "dataframe_for_city_", city,".csv"))
}
For net stumblers, I expand the answer of emilliman5 for larger (think of writing multi-GB a lot faster) datasets with data.table
:
library(data.table)
DT <- data.table(ID = c(1, 1, 2, 3, 3),
City = c("a", "a", "b", "c", "c"),
Qty = c(20, 14, 40, 50, 60))
# setkeyv(DT, 'City') # check if you really need a key: https://stackoverflow.com/questions/20039335/what-is-the-purpose-of-setting-a-key-in-data-table
invisible(lapply(unique(DT[, City]), function(city)
fwrite(x = subset(DT, City == city),
file = paste0("~/", "DT_for_city_", city,".csv"))))