我想将城市智慧数据导出到csv文件,因为我遵循以下静态方法
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)
#3>同样#3
请帮助它转换为动态代码。
提前致谢
答案 0 :(得分:2)
我会做类似的事情:
for (cit in unique(df$city)) {
write.csv(
x = subset(df, city == cit),
file = paste0(cit, ".csv"),
row.names = FALSE
)
}
<强> PS。强>
通常小写文件名是首选,因此我会将file = paste0(cit, ".csv")
转换为file = tolower(paste0(cit, ".csv"))
答案 1 :(得分:1)
@ snoram的答案应该运作良好,所以请考虑这只是做同样事情的另一种方式。我是data.table
的粉丝,我喜欢它的一个方面是调用函数和by
调用:
library( data.table )
setDT( df )
df[ , write.csv( .SD,
paste0( city[1], ".csv" ),
row.names = FALSE ),
by = city ]
.SD
此处代表df
的每个子集;每个值city
一个。
city[1]
从city
获取.SD
的第一个值(该列将一直填充一个值)。
答案 2 :(得分:1)
你也可以使用split来破坏列表中的df,然后循环:
for (i in split(df,city)){
write.csv(i,paste0(i$city[1],".csv"))
}