使用R将多个数据帧写入.csv文件

Dav*_*son 4 r lapply export-to-csv

我使用lapply将函数应用于许多数据框:

data.cleaned <- lapply(data.list, shooter_cleaning)
Run Code Online (Sandbox Code Playgroud)

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

names(data.cleaned) <- subject.names
Run Code Online (Sandbox Code Playgroud)

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

write.csv(x, "100.csv", row.names = F)
Run Code Online (Sandbox Code Playgroud)

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

Ben*_*Ben 12

这是一个与Richard的评论相关的独立示例,但使用列表中数据框的名称作为CSV文件的文件名:

# 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))
Run Code Online (Sandbox Code Playgroud)


Ric*_*loo 6

这是一个常见的操作。您需要将数据帧拆分为多个list数据帧,然后将它们写入许多单独的 csv。我将演示 2 种使用 Base R 的方法和 2 种使用 tidyverse 的方法。

碱基R

循环for使迭代变得非常明确。

# example data.frame
df  <- data.frame(x = 1:4, y = c("a", "a", "b", "b"))

# split the dataframe into a list by the y column
l  <- split(df, df$y)

# make filepaths from list names, which are unique values of the y column
file_out <- paste0(names(l), ".csv")

# iterate over the list and the vector of list names to write csvs
for(i in 1:length(l)) {
  write_csv(l[[i]], file_out[i])
}
Run Code Online (Sandbox Code Playgroud)

或者使用mapply()

mapply(
  function(x, y) write_csv(x, y), 
  l, 
  file_out
)
Run Code Online (Sandbox Code Playgroud)

整洁宇宙方法

library(tidyverse)

# we pass walk2 two inputs: a list of dataframes (.x) and filepaths (.y)
# `walk` is a silent `map` that doesn't print output to the console
walk2(l, file_out, ~write_csv(.x, .y))
Run Code Online (Sandbox Code Playgroud)

或者,避免中间变量:

df %>% 
  group_split(y) %>% 
  walk(~write_csv(.x, paste0(.x$y[1], ".csv")))
Run Code Online (Sandbox Code Playgroud)