[英]Write.table with a fixed number of columns
I have created a very large data frame in R and I want to output a number of subsets and save them as csvs. 我在R中创建了一个非常大的数据框,我想输出许多子集并将其保存为csvs。 However, I only want to keep a subset of the columns (namely bin and volume). 但是,我只想保留列的子集(即bin和volume)。 What is the easiest way to do this considering I am running a loop which needs to use the od field? 考虑到我正在运行一个需要使用od字段的循环,最简单的方法是什么?
#create data frame
od <-c("520_513", "520_513", "520_513", "520_513", "520_513",
"517_620", "517_620", "517_620", "517_620", "517_620")
bin <-c(1,2,3,4,5,1,2,3,4,5)
volume<-c(1,0,4,5,6,4,4,5,6,6)
df <-data.frame(od, bin, volume)
df1 <-split(df,df$od)
#output csvs
df1 <-for(n in names(df1))
write.table(df1[[n]],
row.names=F,
col.names=F,
sep=",",
file=paste( n,".csv"))
This is the output I get for 517_620: 这是我对517_620的输出:
od bin volume
--------------------------------
517_620 1 4
517_620 2 4
517_620 3 5
517_620 4 6
517_620 5 6
But I want this: 但是我想要这个:
bin volume
--------------------
1 4
2 4
3 5
4 6
5 6
Thanks! 谢谢!
Assuming you really want comma-separated files and not the whitespace separation that you illustrated, then make a couple of mods to your for
-loop: 假设您确实想要逗号分隔的文件,而不是您说明的空格分隔,然后for
循环制作几个mod:
for(n in names(df1)) # the assignment would destroy the df1 object
write.table(df1[[n]][ , 2:3], # use only cols 2 and 3
row.names=F,
col.names=F,
sep=",",
file=paste0( n,".csv")) # change to paste0 to avoid spaces
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.