简体   繁体   中英

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. However, I only want to keep a subset of the columns (namely bin and volume). What is the easiest way to do this considering I am running a loop which needs to use the od field?

#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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM