按行分割数据框并另存为csv [英] Split a data frame by rows and save as csv
问题描述
我只有一个数据框,想要按行拆分数据框,将几个新数据框分配给新变量,然后将它们另存为csv文件.
I just have a data frame and want to split the data frame by rows, assign the several new data frames to new variables and save them as csv files.
a <- rep(1:5,each=3)
b <-rep(1:3,each=5)
c <- data.frame(a,b)
# a b
1 1 1
2 1 1
3 1 1
4 2 1
5 2 1
6 2 2
7 3 2
8 3 2
9 3 2
10 4 2
11 4 3
12 4 3
13 5 3
14 5 3
15 5 3
我想按列a拆分c.也就是说,列a中的所有行均是1,从c中拆分出来并将其分配给A并将A保存为A.csv. B.csv与a.列中的所有2相同. 我能做的就是
I want to split c by column a. i.e all rows are 1 in column a are split from c and assign it to A and save A as A.csv. The same to B.csv with all 2 in column a. What I can do is
A<-c[c$a%in%1,]
write.csv (A, "A.csv")
B<-c[c$a%in%2,]
write.csv (B, "B.csv")
...
如果我有1000行并且会有很多子集,我只是想知道是否有一种简单的方法可以通过使用for循环来做到这一点?
If I have 1000 rows and there will be lots of subsets, I just wonder if there is a simple way to do this by using for loop?
推荐答案
split()
函数对于拆分数据帧非常有用.另外,您可以在此处使用lapply()
-它应该比循环更有效.
The split()
function is very useful to split data frame. Also, you can use lapply()
here - it should be more efficient than a loop.
dfs <- split(c, c$a) # list of dfs
# use numbers as file names
lapply(names(dfs),
function(x){write.csv(dfs[[x]], paste0(x,".csv"),
row.names = FALSE)})
# or use letters (max 26!) as file names
names(dfs) <- LETTERS[1:length(dfs)]
lapply(names(dfs),
function(x){write.csv(dfs[[x]],
file = paste0(x,".csv"),
row.names = FALSE)})
这篇关于按行分割数据框并另存为csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!