如何在单独的csv文件中保存for循环的输出?

时间:2017-08-13 01:28:39

标签: r csv for-loop

作为我在下面附加的图片和代码,我有一组交易数据,每行都有其行业名称。

可重复的示例数据:

structure(list(Date = c(1201, 1201, 1201, 1201, 1201, 1201, 1201, 
1201, 1201, 1201), Sex = c("Male", "Male", "Female", "Male", 
"Male", "Female", "Male", "Female", "Male", "Male"), Age = c(10, 
15, 20, 15, 40, 50, 20, 30, 50, 20), City = c("Pheonix", "Atlanta", 
"Las Vegas", "Las Vegas", "Denver", "Pheonix", "Atlanta", "Las Vegas", 
"Las Vegas", "Minneapolis"), State = c("Arizona", "Georgia", 
"Nevada", "Nevada", "Colorado", "Arizona", "Georgia", "Nevada", 
"Nevada", "Minesota"), Industry = c("food", "furniture", "clothes", 
"transportation", "leisure", "food", "furniture", "food", "transportation", 
"furniture"), `no.of users` = c(48, 50, 83, 111, 186, 196.7, 
230.4, 264.1, 297.8, 331.5), `no. of approval cases` = c(48, 
21, 25, 48, 70, 63.7, 70.8, 77.9, 85, 92.1), `Total spending` = c(1541000, 
512000, 1757000, 1117000, 1740500, 1634700, 1735100, 1835500, 
1935900, 2036300)), .Names = c("Date", "Sex", "Age", "City", 
"State", "Industry", "no.of users", "no. of approval cases", 
"Total spending"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-10L))

我想要做的是仅对行业名称与条件匹配的行进行子集化,并将其作为单独的csv文件导出,并使用与其行业名称对应的文件名称。 例如,我们说我有一个

列表
 current_industry<-c("food","furniture")

首先,我想对行业名称与"food"匹配的行进行子集化,然后将其保存到csv files名称&#39; food&#39;,然后对行业名称匹配的以下行进行子集化"furniture"并将其保存为单独的csv files名称&#39;家具&#39;。

我写了for循环来执行此操作,但这不起作用,因为以下子集数据事先替换了一个。

for(i in current_industry){
  write.csv(subset(masterset, industry == i), "i.csv")} 

enter image description here

1 个答案:

答案 0 :(得分:2)

我认为这会奏效。运行此代码后,您会在工作目录中找到food.csvfurniture.csv

current_industry <- c("food", "furniture")

for (i in current_industry){
  dt2 <- subset(dt, Industry %in% i)
  write.csv(dt2, paste0(i, ".csv"), row.names = FALSE)
}

更新

您也可以考虑以下内容。此代码将所有行业保存为工作目录中的单独CSV文件。

dt_list <- split(dt, f = dt$Industry)

lapply(dt_list, function(dt){
  write.csv(dt, paste0(unique(dt$Industry), ".csv"), row.names = FALSE)
})

以下内容仅保存foodfurniture。关键是将current_industry用于子集dt_list

dt_list <- split(dt, f = dt$Industry)

dt_list2 <- dt_list[current_industry]

lapply(dt_list2, function(dt){
  write.csv(dt, paste0(unique(dt$Industry), ".csv"), row.names = FALSE)
})