write.csv在数据帧列表上

时间:2017-02-04 23:45:44

标签: r

我试图从单独目录中的列表中保存大量数据帧。我的代码有问题:

lapply(na_s, function (x) write.csv(na_s[[x]],file = paste('/na_s_daily/',names (na_s[x]),'.csv',sep=""), row.names = F)) 

错误代码:

Error in na_s[[x]] : invalid subscript type 'list'

任何人都可以看到我做错了什么?

2 个答案:

答案 0 :(得分:1)

问题是输入x是一个不是列表元素的数字。 尝试

SELECT 
 cle.[Primary Key]AS Vendor
, cle.[New Value] 
, ven.Name
, CAST(cle.[Date and Time] AS DATE) AS LogDate
, CAST(cle.Time AS TIME(0)) AS LogTime 
, cle.[Field No_]
, cle.[Type of Change]
, cle.[User ID]
 FROM dbo.[YourCompany$Change Log Entry] cle
  left outer JOIN dbo.YourCompany$Vendor ven
  ON cle.[Primary Key] = ven.No_ 
  WHERE 
  cle.[Table No_] = 23
  and cle.[Field No_] = 1  
 AND cle.[Type of Change] = 0
 ORDER BY LogDate, LogTime, Vendor

请注意,上面的内容也会返回数据框列表。因此,如果您只需要将列表中的每个元素保存为目录中的数据框,只需执行

即可
 lapply(1:length(na_sx),  function (x) write.csv(na_s[[x]],file = paste('./na_s_daily/','na_', names (na_s[x]),'.csv',sep=""), row.names = F)) 

答案 1 :(得分:1)

如果您想使用列表名称,我建议您使用mapply。您还需要确保输出目录在使用之前存在,否则您将收到错误。我还将paste更改为paste0paste(x, sep = ""))。

na_s <- list("one" = mtcars, "two" = mtcars, "three" = mtcars)

mapply(function (x,y) write.csv(x, file = paste0('./na_s_daily/', y, '.csv'), row.names = F), na_s, names(na_s))