将环境中的数据帧写入单独的csv文件中 [英] Write data frames in environment into separate csv files

查看:85
本文介绍了将环境中的数据帧写入单独的csv文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码将R环境中的所有数据集导出到单独的csv文件中.

I am trying to export all data sets in R environment into separate csv files using the code below.

由于某些原因,导出的数据集为空.

For some reason, the exported datasets are empty.

files <- ls()
pattern <- ".csv"

for (i in 1:length(files)) {
  write.csv(files[i], paste(files[i], pattern, sep = ""))
}

推荐答案

此处的问题是ls()返回环境中对象的名称,而不是对象本身.这意味着您的循环正在尝试将单个字符串导出为csv文件.

The problem here is that ls() returns the names of the objects in the environment, not the objects themselves. This means that your loop is trying to export single character strings as a csv files.

要解决此问题,您需要使用mget(),如下所示:

To solve this you need to use mget() as follows:

files <- mget(ls())

for (i in 1:length(files)){
  write.csv(files[[i]], paste(names(files[i]), ".csv", sep = ""))
}

注意:您需要谨慎使用正确的方式使用[[i]][i].

Note: you need to be careful that you use [[i]] and [i] the correct way round.

这篇关于将环境中的数据帧写入单独的csv文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆