Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

export to csv - Writing multiple data frames into .csv files using R

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

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

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

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)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...