使用R将多个数据帧写入.csv文件 [英] Writing multiple data frames into .csv files using R

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

问题描述

我曾经用lapply将函数应用于多个数据帧:

I have used lapply to apply a function to a number of data frames:

data.cleaned <- lapply(data.list, shooter_cleaning)

然后根据其主题编号(例如100)在列表中将每个结果数据帧标记为:

And then labeled each of the resulting data frames in the list according to their subject number (e.g., 100):

names(data.cleaned) <- subject.names

我要做的是根据主题编号将每个新数据帧另存为一个单独的.csv文件.例如,对于主题100,我希望将.csv文件标记为"100.csv".通常要这样做(对于单个数据帧),我只会写(其中x是数据帧):

What I want to do is to save each new data frame as an individual .csv file based on its subject number. For example, for subject 100 I'd like the .csv file to be labeled as "100.csv" Normally to do this (for a single data frame) I would just write (where x is the data frame):

write.csv(x, "100.csv", row.names = F)

但是,显然,使用lapply对我的数据帧列表执行此操作只会生成"100.csv"的许多副本,而我希望文件根据其主题号是唯一的.如何(适用于?)将这些数据帧中的每一个保存到它们自己的唯一.csv文件中?

But, obviously using lapply to do this for my list of data frames will just produce many copies of "100.csv" when instead I would like the files to be unique, based on their subject number. How can I (use apply to?) save each of these data frames to their own unique .csv file?

推荐答案

这是一个

Here's a self-contained example along the lines of Richard's comment, but uses the names of the dataframes in the list as filenames for the CSV files:

# Create a list of n data frames

n <- 10

my_list <- lapply(1:n, function(i)  data.frame(x = rnorm(10), y = rnorm(10)) )

# name the data frames

names(my_list) <- letters[1:n]

# save each new data frame as an individual .csv file based on its name

lapply(1:length(my_list), function(i) write.csv(my_list[[i]], 
                                      file = paste0(names(my_list[i]), ".csv"),
                                      row.names = FALSE))

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

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